buffer_rgba() 神秘地向 matplotlib 图形添加空格

CPa*_*yne 5 python matplotlib

我在笔记本中有一些简单的代码,可以使用 matplotlib 可视化图像

f = plt.figure()
plt.imshow(rgb_img)
# f.tight_layout(pad=0) doesn't fix the issue
f.canvas.draw()
# save figure as a np array for easy visualization w/ imshow later
fig_as_np_array = np.array(f.canvas.renderer.buffer_rgba())
Run Code Online (Sandbox Code Playgroud)

此时一切看起来都很好:

在此输入图像描述

然后,我尝试查看保存的 np 数组 ( plt.imshow(fig_as_np_array)),我希望它显示相同的内容,但我得到了奇怪的空白加上一组新的轴:

在此输入图像描述

我一生都无法弄清楚是什么添加了额外的空白/轴,形状也略有不同:

print(f'rgb shape: {rgb_img.shape}') # prints: rgb shape: (480, 640, 3)
print(f'saved fig shape: {fig_as_np_array.shape}') # prints: saved fig shape: (288, 432, 4)
Run Code Online (Sandbox Code Playgroud)

知道发生了什么(fwiw我正在笔记本上想象这一点)。谢谢你的时间

Asm*_*mus 5

如果我正确理解你的问题,你必须确保创建具有正确尺寸的图形,然后在写入缓冲区之前删除轴(通过ax.set_axis_off())和图像周围的图形框架(通过frameon=False),请参阅评论以下:

\n
import matplotlib as mpl\nmpl.use("tkagg") # <\xe2\x80\x94 you may not need this, \n                 #    but I had to specify an agg backend manually\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\n\n## image taken from\n# "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Empty_road_at_night.jpg/1024px-Empty_road_at_night.jpg"\nfilename = "1024px-Empty_road_at_night.jpg"\nim = mpimg.imread(filename)\n\n## create the figure with the correct dpi & resolution\n#  and make sure that you specify to show "no frame" around the image\nfigure_dpi = 72\nfig = plt.figure(figsize=(1024/figure_dpi,768/figure_dpi),dpi=figure_dpi,frameon=False,facecolor="w")\nax = fig.add_subplot()\n\n## turn of axes, make imshow use the whole frame\nax.set_axis_off()\nplt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)\nplt.margins(0,0)\n\n## show image\nax.imshow(im,zorder=0,alpha=1.0,origin="upper")\n## add some text label\nax.text(300,600,"this is the middle lane",fontsize=30,color="w")\n\ndef fig2rgb_array(fig):\n    """adapted from: /sf/ask/1535776091/"""\n    fig.canvas.draw()\n    buf = fig.canvas.tostring_rgb()\n    ncols, nrows = fig.canvas.get_width_height()\n    print("to verify, our resolution is: ",ncols,nrows)\n    return np.frombuffer(buf, dtype=np.uint8).reshape(nrows, ncols, 3)\n\n## make a new figure and read from buffer\nfig2,ax2 = plt.subplots()\nax2.imshow(fig2rgb_array(fig))\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

产量(请注意,现在图像周围只有一组轴,而不是两组):

\n

顶部有文本的缓冲图像

\n