【发布时间】:2017-08-23 03:29:25
【问题描述】:
有没有办法将特定 Axes 对象的内容呈现为图像,作为 Numpy 数组?我知道您可以对整个图形执行此操作,但我想获取特定轴的图像。
我尝试渲染的轴包含一个图像(使用 imshow 绘制),顶部绘制了一些线条。理想情况下,渲染的 ndarray 将只包含这些元素,没有刻度线、边框等。
更新:
我忘了提到我正在寻找一种不需要保存图像文件的解决方案。
我编写了以下示例,几乎可以实现这一点,只是它不保留图像分辨率。任何关于我可能做错的提示将不胜感激:
import matplotlib.pylab as plt
import numpy as np
def main():
"""Test for extracting pixel data from an Axes.
This creates an image I, imshow()'s it to one Axes, then copies the pixel
data out of that Axes to a numpy array I_copy, and imshow()'s the I_copy to
another Axes.
Problem: The two Axes *look* identical, but I does not equal I_copy.
"""
fig, axes_pair = plt.subplots(1, 2)
reds, greens = np.meshgrid(np.arange(0, 255), np.arange(0, 122))
blues = np.zeros_like(reds)
image = np.concatenate([x[..., np.newaxis] for x in (reds, greens, blues)],
axis=2)
image = np.asarray(image, dtype=np.uint8)
axes_pair[0].imshow(image)
fig.canvas.draw()
trans = axes_pair[0].figure.dpi_scale_trans.inverted()
bbox = axes_pair[0].bbox.transformed(trans)
bbox_contents = fig.canvas.copy_from_bbox(axes_pair[0].bbox)
left, bottom, right, top = bbox_contents.get_extents()
image_copy = np.fromstring(bbox_contents.to_string(),
dtype=np.uint8,
sep="")
image_copy = image_copy.reshape([top - bottom, right - left, 4])
image_copy = image_copy[..., :3] # chop off alpha channel
axes_pair[1].imshow(image_copy)
print("Are the images perfectly equal? {}".format(np.all(image == image_copy)))
plt.show()
if __name__ == '__main__':
main()
【问题讨论】:
-
您希望生成的图像与原始图像一样大(以像素为单位),还是您不关心分辨率?
-
是的,渲染的图像应该和我在绘图时在屏幕上看到的分辨率相同。
标签: matplotlib