Home > Back-end >  Can image displayed by plt.imshow() be saved as a numpy array?
Can image displayed by plt.imshow() be saved as a numpy array?

Time:09-24

This is a line from my code:

plt.imshow(Equalized, cmap=plt.get_cmap('gray'), vmin = 0.55, vmax = 0.80)

Here, Equalized is a 2-D image. The image displayed by this is the following:

enter image description here

fig(i)

Now, I wish to save the exact output image (without axes, borders, etc.) - enter image description here

fig(ii)

as a numpy array for further manipulations. How can I do that? If there is no way to do that, then in that case, kindly help me by telling me how can I replicate the effects of cmap, vmin, vmax inside imshow() to generate the exact replica of the output.

Edit: On incorporating the answer of Lucas M. Uriarte as given below, I am able to save it as a numpy array in a variable, but on displaying it I get the following image:

fig(iii)

This image is the same as the Equalized image in the beginning. Can I get fig(ii) as a numpy array in any way?

CodePudding user response:

yes, it is possible if you store the output as variable.

output = plt.imshow(Equalized, cmap=plt.get_cmap('gray'), vmin = 0.55, vmax = 0.80)
# output should be a matplotlib.image.AxesImage object
np_array = output.get_array() 

Edit for updated question

After verifying what the color map and vmin vmax does to the data matrix of the figure. the following lines demonstrate that the matrix under the figure is not modified, but only the scale of the colormap is changed, between images.

fig1 = plt.imshow(Equalized, cmap=plt.get_cmap('gray'), vmin = 0.55, vmax = 0.80)
fig2 = plt.imshow(Equalized)

(fig1.get_array()  == fig2.get_array() ).all()
>>> True

That is to say if you want to normalize you data you should do it previously, vmin vmax do a linear normalization. you can do that on your data as follow

normalized_matix = data_norm = (Equalized - vmin) / (vmax - vmin)

and you should always use the colormap in gray if you want it to be gray

  • Related