For example, I plot a figure using matplotlib as follows:
plt.figure(figsize=(10,10))
plt.imshow(output_fig, zorder=0,cmap="gray")
plt.scatter(x,y,color='k')
if I use:
plt.savefig(figname,fotmat=figtype)
I will save it as a figure file. However, I want so save it to a matrix, or numpy array, such that each element saves the scale value of each pixel of the figure. How can I do this? I find solutions saving the RGB values. But I hope to save a greyscale figure. Thank you all for helping me!
To save the grayscale image generated by Matplotlib's plt. imshow() , add another line plt. savefig("gray. jpg") .
To save the Numpy array as a local image, use the save() function and pass the image filename with the directory where to save it. This will save the Numpy array as a jpeg image.
Saving a plot on your disk as an image file 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.
Once you have a ploted data (self contained example bellow):
import numpy as np
import matplotlib.pyplot as plt
from skimage import data, color
img = data.camera()
x = np.random.rand(100) * img.shape[1]
y = np.random.rand(100) * img.shape[0]
fig = plt.figure(figsize=(10,10))
plt.imshow(img,cmap="gray")
plt.scatter(x, y, color='k')
plt.ylim([img.shape[0], 0])
plt.xlim([0, img.shape[1]])
The underlying data can be recovered as array by using fig.canvas
(the matplotlib's canvas). First trigger its drawing:
fig.canvas.draw()
Get the data as array:
width, height = fig.get_size_inches() * fig.get_dpi()
mplimage = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)
If you want your array to be the same shape as the original image you will have to play with figsize
and dpi
properties of plt.figure()
.
Last, matplotlib returns an RGB image, if you want it grayscale:
gray_image = color.rgb2gray(mplimage)
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