gpt4 book ai didi

python - buffer_rgba() 神秘地向 matplotlib 图添加了空格

转载 作者:行者123 更新时间:2023-12-04 15:22:23 24 4
gpt4 key购买 nike

我在笔记本中有一些简单的代码来使用 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())
在这一点上,一切看起来都很好:
enter image description here
然后我尝试查看保存的 np 数组( plt.imshow(fig_as_np_array) ),我希望它显示相同的内容,但我得到了奇怪的空白加上一组新的轴:
enter image description here
我一生都无法弄清楚是什么添加了额外的空白/轴,形状也略有不同:
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)
知道发生了什么(我正在笔记本中想象这个)。谢谢你的时间

最佳答案

如果我正确理解您的问题,您必须确保创建具有正确尺寸的图形,然后在写入之前删除轴(通过 ax.set_axis_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()
产生(注意现在图像周围只有一组轴,而不是两个):
buffered image with text on top

关于python - buffer_rgba() 神秘地向 matplotlib 图添加了空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63027743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com