How to save an array as a grayscale image using matplotlib / numpy?

I am trying to save a 128x128 pixel numpy array in grayscale. I just thought that the pyplot.imsave function would do the job, but it isn’t, it somehow converts my array into an RGB image. I tried to force the Gray color code to be set during conversion, but although the saved image appears in grayscale, it still has a size of 128x128x4. Here is an example of the code I wrote to show the behavior:

import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mplimg from matplotlib import cm x_tot = 10e-3 nx = 128 x = np.arange(-x_tot/2, x_tot/2, x_tot/nx) [X, Y] = np.meshgrid(x,x) R = np.sqrt(X**2 + Y**2) diam = 5e-3 I = np.exp(-2*(2*R/diam)**4) plt.figure() plt.imshow(I, extent = [-x_tot/2, x_tot/2, -x_tot/2, x_tot/2]) print I.shape plt.imsave('image.png', I) I2 = plt.imread('image.png') print I2.shape mplimg.imsave('image2.png',np.uint8(I), cmap = cm.gray) testImg = plt.imread('image2.png') print testImg.shape 

In both cases, the results of the print function (128,128,4).

Can someone explain why the imsave function creates these measurements, although my input array has a brightness type? And of course, does anyone have a solution to save the array in a standard format in grayscale?

Thanks!

+5
source share
2 answers

With PIL it should work as follows

 import Image I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8) img = Image.fromarray(I8) img.save("file.png") 
+5
source

I did not want to use PIL in my code, and, as noted in the question, I ran into the same problem with pyplot, where even in grayscale the file is saved in the MxNx3 matrix.

Since the actual image on disk was not important to me, I ended up writing the matrix as is and reading it “as is” using the numpy save and load methods:

 np.save("filename", image_matrix) 

and

 np.load("filename.npy") 
-1
source

Source: https://habr.com/ru/post/1206869/


All Articles