简体   繁体   English

python:如何直接从字节字符串变量显示图像?

[英]python: how to display a image directly from bytes string variable?

I have a byte string variable fig which I get from another API.我有一个从另一个 API 获得的字节字符串变量fig

print(fig)

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\....'

How can I display a picture directly from this variable?如何直接从此变量显示图片?

PS: I don't want to store this variable in a PNG file, then use matplotlib to read and show. PS:我不想把这个变量存成PNG文件,然后用matplotlib读取显示。

I have tried PIL.Image.frombytes https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.frombytes however, I don't know which mode( https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes ) I have to choose.我试过 PIL.Image.frombytes https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.frombytes但是,我不知道哪种模式( https://pillow.readthedocs .io/en/stable/handbook/concepts.html#concept-modes )我必须选择。 It reports errors when I tried several modes.当我尝试几种模式时它会报告错误。

Something like this should help:这样的事情应该会有所帮助:

import numpy as np
import cv2

nparr = np.fromstring(img_str, np.uint8)
image = cv2.imdecode(nparr, -1)

cv2.imshow('image', image)
cv2.waitKey(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM