读取打印输出而不将其保存为文件

2024-04-25 01:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我将打印的输出保存如下:

ImageName='MyGraph.jpg'    
myfig=df.plot(kind='bar')
img=myfig.get_figure()
img.savefig(ImageName)

然后用以下文字阅读:

savedimage=cv2.imread(ImageName)

我想跳过将图形保存到图像中,而是直接读取图形,如下所示:

myfig=df.plot(kind='bar')
img=myfig.get_figure()
savedimage=cv2.imread(img)

这不起作用,可能是因为imread()需要一个文件。有办法做到这一点吗?我应该使用不同的方法吗?如果是,是什么

我希望这样做,因为我不需要映像的物理副本,而且我倾向于认为此操作导致的I/o可能会对性能产生影响,因此希望跳过文件保存过程。这可能吗


Tags: 文件图形dfimggetplotbarcv2
1条回答
网友
1楼 · 发布于 2024-04-25 01:27:38

可以使用fig.canvas.tostring_rgb()np.fromstring提取像素值:

fig, ax = plt.subplots()
df.plot(kind='bar', ax=ax)

# need to draw first
fig.canvas.draw()
width, height = fig.canvas.get_width_height()

img = np.frombuffer(fig.canvas.tostring_rgb(), 
                    dtype=np.uint8
                   ).reshape(height, width,-1)  # also need to reshape

img_bgr = cv2.cvtColor(img, cv2.RGB2BGR)

相关问题 更多 >