繁体   English   中英

是否可以访问 matplotlib 艺术家的光栅化表示?

[英]Is it possible to access the rasterized representation of a matplotlib Artist?

是否可以访问 matplotlib 艺术家的光栅化表示? 我知道调用set_rasterized(True)会产生光栅化图形导出。 但是,我还没有找到直接访问该位图的方法。

假设光栅化仅在实际渲染图形时发生,我认为最简单的解决方案是两步过程,您实际上将光栅图像存储到文件并再次加载它:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

## create a figure, here 72 dpi at 10 inch figure size yields 720x720px
fig = plt.figure(frameon=False,dpi=72,figsize=(10,10))
## make the axis full size
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_aspect(1)
fig.add_axes(ax)

## actually plot something that has obviously transparent regions,
#  e.g. a rectangular shape that's twisted by 45 degrees
d = np.arange(100).reshape(10, 10)
x, y = np.meshgrid(np.arange(11), np.arange(11))
theta = 0.25*np.pi
xx = x*np.cos(theta) - y*np.sin(theta)
yy = x*np.sin(theta) + y*np.cos(theta)

## make sure you've rasterized the artist
m = ax.pcolormesh(xx, yy, d)
m.set_rasterized(True)
ax.set_axis_off()

## store the image
plt.savefig("/tmp/test.png")

## load the image
img = mpimg.imread("/tmp/test.png")
print(img.shape) # this should now be (720,720,4), i.e. an RGBA image 
print(img[:1,:1])# this should be [[[1. 1. 1. 0.]]] ,i.e. a white, 100% transparent pixel

注意:可能有更好的解决方案,但是嘿,它有效:-)

更新:

要“直接”访问图像,您可以做的是绘制画布(例如通过plt.show() ,然后读取缓冲区:

# … the initial plotting code from above goes here
plt.show()
s, (width, height) = fig.canvas.print_to_buffer()
print(width,height) ## in my case with a high-dpi display this yields 1440x1440 !
X = np.frombuffer(s, np.uint8).reshape((height, width, 4))
print(X.shape) 

哪个应该产生 (720,720,4) 但在我的情况下是 (1440, 1440, 4) 由于我的视网膜显示。 为了避免这种情况,您可以使用:

from matplotlib.backends.backend_agg import FigureCanvasAgg

# … plotting code goes here
canvas = FigureCanvasAgg(fig)

# code from update goes here:
X = np.frombuffer(s, np.uint8).reshape((height, width, 4))
print(X.shape)
# now yields (720, 720, 4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM