Python buffer_rgba()神秘地将空白添加到matplotlib图中

Python buffer_rgba()神秘地将空白添加到matplotlib图中,python,matplotlib,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.buffe

我在笔记本中有一些简单的代码,可以用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())
在这一点上,一切看起来都很好:

然后我尝试查看保存的np数组(
plt.imshow(fig\u as\u np\u 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)

知道发生了什么事吗(fwiw我在笔记本上看到了这一点)。感谢您的时间

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

import matplotlib as mpl
mpl.use("tkagg") # <— you may not need this, 
                 #    but I had to specify an agg backend manually
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

## image taken from
# "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Empty_road_at_night.jpg/1024px-Empty_road_at_night.jpg"
filename = "1024px-Empty_road_at_night.jpg"
im = mpimg.imread(filename)

## create the figure with the correct dpi & resolution
#  and make sure that you specify to show "no frame" around the image
figure_dpi = 72
fig = plt.figure(figsize=(1024/figure_dpi,768/figure_dpi),dpi=figure_dpi,frameon=False,facecolor="w")
ax = fig.add_subplot()

## turn of axes, make imshow use the whole frame
ax.set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.margins(0,0)

## show image
ax.imshow(im,zorder=0,alpha=1.0,origin="upper")
## add some text label
ax.text(300,600,"this is the middle lane",fontsize=30,color="w")

def fig2rgb_array(fig):
    """adapted from: https://stackoverflow.com/questions/21939658/"""
    fig.canvas.draw()
    buf = fig.canvas.tostring_rgb()
    ncols, nrows = fig.canvas.get_width_height()
    print("to verify, our resolution is: ",ncols,nrows)
    return np.frombuffer(buf, dtype=np.uint8).reshape(nrows, ncols, 3)

## make a new figure and read from buffer
fig2,ax2 = plt.subplots()
ax2.imshow(fig2rgb_array(fig))
plt.show()
将matplotlib导入为mpl

mpl.use(“tkagg”)#
fig_as_np_array
正如您正确命名的那样,是整个图形,而不仅仅是Axes对象的内容。大小(形状)取决于您的体形的大小和dpi值(
rcParams['figure.figsize']
plt.rcParams['figure.dpi']
)谢谢@Stef,但我仍然无法删除空白。我已经尝试设置所有我认为相关的参数:
plt.rcParams['figure.subplot.bottom']=0 plt.rcParams['figure.subplot.wspace']=0 plt.rcParams['figure.subplot.left']=0 plt.rcParams['figure.subplot.right']=1
,但是在imshow结果上没有任何变化,我无法完全掌握你的思维过程。您拥有要显示的图像。然后显示它。然后保存整个图形并显示它,即使您只想显示您首先已经拥有的图像。你到底想做什么?@user8408080,抱歉搞混了。基本上,我想在图像中添加一些标签(例如plt.text(),等等),然后将图像与标签一起保存为numpy数组,这样我就可以将其保存到磁盘并在以后可视化。在此之前,我想了解如何控制图形,使其不会在图像周围添加我无法控制的空白。理想情况下,我只希望图像完全占据图形,这可能是一个。是否确实要栅格化图形中的所有对象,然后再重新栅格化?或者您可能只是想保存figure对象?为什么你甚至需要保存中间的数字;也许你可以在一个脚本中完成所有步骤?非常感谢!让我重新制作赏金,这样我就可以给你了!我也意识到我的W和H变量在
figsize
中被翻转,这使问题更加严重