I have the following code
import scipy.misc
import matplotlib.pyplot as plt
a = plt.imshow(scipy.misc.lena())
and what I'm hoping to achieve is get the data on lena by accessing a
or it's children.
The reason is I'll be accessing the image as plt.gcf()
or plt.gca()
imshow. The matplotlib function imshow() creates an image from a 2-dimensional numpy array. The image will have one square for each element of the array. The color of each square is determined by the value of the corresponding array element and the color map used by imshow() .
imshow() Function: The imshow() function in pyplot module of matplotlib library is used to display data as an image; i.e. on a 2D regular raster. Parameters: This method accept the following parameters that are described below: X: This parameter is the data of the image.
show() displays the figure (and enters the main loop of whatever gui backend you're using). You shouldn't call it until you've plotted things and want to see them displayed. plt. imshow() draws an image on the current figure (creating a figure if there isn't a current figure).
a
should be a matplotlib.image.AxesImage
instance, in which case you can use
a.get_array()
and
a.set_array(data)
The array is stored as a masked array
.
Example
There's an official example available at http://matplotlib.org/examples/animation/dynamic_image.html.
Direct access
You can also use
a._A
to access the array data directly, though I imagine that the getters and setters are the preferred method.
### get image from the plot ###
plt.figure()
...
plt.imshow(image)
# remove white padding
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
plt.axis('off')
plt.axis('image')
# redraw the canvas
fig = plt.gcf()
fig.canvas.draw()
# convert canvas to image using numpy
img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
# opencv format
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
plt.close()
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