Reputation: 1725
I have a byte string variable fig
which I get from another API.
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.
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. It reports errors when I tried several modes.
Upvotes: 2
Views: 1523
Reputation: 23556
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)
Upvotes: 3