I have the following python code that downloads a set of images to train a model with...
from matplotlib import pyplot as plt
import numpy as np
import tensorflow as tf
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5
print(str(type(train_images[0,0])))
for i in range(len(train_images)):
plt.imsave('train_images\\' str(train_labels[i]) '.jpg', train_images[i, :])
I'm trying to save these images to files, I've determined that this is a 4d array based on the number of times I can index it before getting an error message about trying to index a scalar.
PS C:\Users\David\Desktop\ai> python .\images.py
<class 'numpy.ndarray'>
Traceback (most recent call last):
File "C:\Users\David\Desktop\ai\images.py", line 13, in <module>
plt.imsave('train_images\\00' str(train_labels[i]) '.jpg', train_images[i, :])
File "C:\python3.9.9\lib\site-packages\matplotlib\pyplot.py", line 2144, in imsave
return matplotlib.image.imsave(fname, arr, **kwargs)
File "C:\python3.9.9\lib\site-packages\matplotlib\image.py", line 1641, in imsave
rgba = sm.to_rgba(arr, bytes=True)
File "C:\python3.9.9\lib\site-packages\matplotlib\cm.py", line 434, in to_rgba
raise ValueError("Third dimension must be 3 or 4")
ValueError: Third dimension must be 3 or 4
PS C:\Users\David\Desktop\ai>
Can anyone show me how to do this?
CodePudding user response:
as soon as I asked I found the answer... the last line needs to look like this:
plt.imsave('train_images\\' str(train_labels[i]) '.jpg', train_images[i, :, :, 0])
CodePudding user response:
The problem is your [i,:])
inside the loop for i in range (len (train_images)). You have to replace it with with [i,:,:, 0])
. The solution is this
for i in range(len(train_images)):
plt.imsave('train_images\\' str(train_labels[i]) '.jpg', train_images[i, :])
from matplotlib import pyplot as plt
import numpy as np
import tensorflow as tf
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5
print(str(type(train_images[0,0])))
for i in range(len(train_images)):
plt.imsave('train_images\\' str(train_labels[i]) '.jpg', train_images[i, :, :, 0])