python - 如何从plt.imshow()获取数据?

时间:2014-04-28 15:32:19

标签: python matplotlib

我有以下代码

import scipy.misc
import matplotlib.pyplot as plt

a = plt.imshow(scipy.misc.lena())

我希望通过访问a或其子女来获取lena的数据。

原因是我将plt.gcf()plt.gca()

访问该图片

2 个答案:

答案 0 :(得分:8)

a应该是matplotlib.image.AxesImage个实例,在这种情况下,您可以使用

a.get_array() 

a.set_array(data)

数组存储为masked array

示例

http://matplotlib.org/examples/animation/dynamic_image.html提供了一个官方示例。

直接访问

您也可以使用

a._A

直接访问数组数据,虽然我认为getter和setter是首选方法。

答案 1 :(得分:0)

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