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

10 投票
2 回答
14006 浏览
提问于 2025-04-18 04:36

我有以下这段代码:

import scipy.misc
import matplotlib.pyplot as plt

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

我希望能通过访问 a 或它的子元素来获取关于 lena 的数据。

这样做的原因是我会通过 plt.gcf()plt.gca() 来访问这个图像。

2 个回答

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

17

a 应该是一个 matplotlib.image.AxesImage 的实例,这样你就可以使用

a.get_array() 

a.set_array(data)

这个数组是以 masked array 的形式存储的。

示例

这里有一个官方示例,可以在这个链接找到:http://matplotlib.org/examples/animation/dynamic_image.html

直接访问

你也可以使用

a._A

直接访问数组数据,虽然我想 getters 和 setters 是更推荐的方法。

撰写回答