首页 > 解决方案 > 是否可以访问 matplotlib 艺术家的光栅化表示?

问题描述

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

标签: pythonmatplotlib

解决方案


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

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)

推荐阅读