I have an (n, m) array that I've been visualizing with matplotlib.pyplot.imshow
. I'd like to save this data in some type of raster graphics file (e.g. a png) so that:
imshow
interpolation='nearest'
in imshow
.)How can I do this?
I've seen some code that can kind of do this by using interpolation='nearest'
and forcing matplotlib to (grudgingly) turn off axes, whitespace, etc. However, there must be some way to do this more directly -- maybe with PIL? After all, I have the underlying data. If I can get an RGB value for each element of the underlying array, then I can save it with PIL. Is there some way to extract the RGB data from imshow
? I can write my own code to map the array values to RGB values, but I don't want to reinvent the wheel, since that functionality already exists in matplotlib.
By default, imshow normalizes the data to its min and max. You can control this with either the vmin and vmax arguments or with the norm argument (if you want a non-linear scaling).
Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.
As you already guessed there is no need to create a figure. You basically need three steps. Normalize your data, apply the colormap, save the image. matplotlib provides all the necessary functionality:
import numpy as np import matplotlib.pyplot as plt # some data (512x512) import scipy.misc data = scipy.misc.lena() # a colormap and a normalization instance cmap = plt.cm.jet norm = plt.Normalize(vmin=data.min(), vmax=data.max()) # map the normalized data to colors # image is now RGBA (512x512x4) image = cmap(norm(data)) # save the image plt.imsave('test.png', image)
While the code above explains the single steps, you can also let imsave
do all three steps (similar to imshow
):
plt.imsave('test.png', data, cmap=cmap)
Result (test.png):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With