Last active
October 23, 2024 18:43
-
-
Save eric-czech/fea266e546efac0e704d99837a52b35f to your computer and use it in GitHub Desktop.
Convert png image bytes to numpy array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from io import BytesIO | |
from PIL import Image | |
def png_bytes_to_numpy(png): | |
"""Convert png bytes to numpy array | |
Example: | |
>>> fig = go.Figure(go.Scatter(x=[1], y=[1])) | |
>>> plt.imshow(png_bytes_to_numpy(fig.to_image('png'))) | |
""" | |
return np.array(Image.open(BytesIO(png))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You may have gotten your raw image bytes in a way that is unsupported by Pillow:
Why did this error occur, even though we went from bytes -> BytesIO -> PIL.Image.Image like in the first example? It is because the
PIL.Image.Image
method.tobytes()
returns the pixel data of an image, not a fully encoded image. When you try to useImage.open
on just pixel data, it can't determine the filetype, because there is no filetype for that data at all, just raw pixels.Fixing our incorrect example: