Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - how to get the data from an plt.imshow()?

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()

like image 396
evan54 Avatar asked Apr 28 '14 15:04

evan54


People also ask

What does PLT Imshow () do?

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() .

How do I use PLT Imshow in Python?

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.

What is the difference between PLT Imshow and PLT show?

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).


2 Answers

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.

like image 86
jmetz Avatar answered Sep 24 '22 12:09

jmetz


### 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()
like image 43
SimoX Avatar answered Sep 24 '22 12:09

SimoX