Problem Description:
When learning the MNIST machine learning introductory course, the attributeerror: module ‘SciPy. Misc’ has no attribute ‘toimage’ error occurs when converting the numpy array into a picture and saving it
the execution code is as follows:
# Save the first 20 images
for i in range(20):
image_array = train_images[i]
#Save file as the format:mnist_train_0.jpg,mnist_train_1.jpg,...
filename = save_dir + '/mnist_train_%d.jpg' %i
#save image_array to image
# use scipy.misc.toimage to convert to image and save
scipy.misc.toimage(image_array, cmin=0.0, cmax=1.0).save(filename)
Crux attribution:
I checked the scene where Python 3 uses the toimage() function on the Internet and found that this function has been deprecated. Many tutorials recommend reducing the version of the third-party SciPy to match the use of the toimage() function. I feel that this is a bit “married down” and can not fundamentally solve the problem. Moreover, the iteration of technology update is inevitable, We need to follow the trend.
Scipy.misc.toimage official latest instructions.
Solution:
Turn the problem into how to save the array as an image?
Method 1: use the .Imwrite()
function of CV2 module
to convert the numpy array into an image and save it. The specific codes are as follows:
cv2.imwrite(filename, image_array) #Mutual transformation of images and numpy arrays using cv2
Method 2: use the .Fromarray()
function under Image
in PIL module
to convert the numpy array into an image and save it. The specific codes are as follows:
from PIL import Image
Image.fromarray((image_array)).save(filename) #Mutual transformation of images and numpy arrays using PIL
# or
Image.fromarray((image_array*255).astype('uint8'), mode='L').convert('RGB').save(filename) # For processing color images
Method 3: use the Matplotlib module
to convert the numpy array into a picture and save it. (including two methods): (1) preferred recommendation: Use the . Imsave()
function under Image
in the Matplotlib module
to convert the numpy array into an image for saving. The specific codes are as follows:
from matplotlib import image
image.imsave(filename,image_array,cmap='gray') # cmap is often used to change the drawing style, such as black and white gray, emerald green virdidis
(2) Not recommended: Use the .Savefig()
function under pyplot
in Matplotlib module
to convert the numpy array into a picture for saving. The generated picture contains coordinate axis and border information. The specific codes are as follows:
import matplotlib.pyplot as plt
# Drawing pictures
plt.imshow(image_array,cmap='gray')
# save image
plt.savefig(filename) # In this case, the picture variable is already specified when drawing the picture, so there is no need to specify it again when saving