2

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.

3
  • Have you looked at pil? Commented May 21, 2020 at 4:42
  • 1
    @MadPhysicist Yes, pillow.readthedocs.io/en/stable/reference/… however, I don't know which mode I can choose. I tried several ones and report error Commented May 21, 2020 at 4:43
  • Could you provide the full PNG? Perhaps dump the string to a file and post it here. Commented May 21, 2020 at 5:24

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.