PNG --> Bytes IO --> numpy conversion using file_uploader?

st.file_uploader returns a io.BytesIO file when I upload an image.

I’d like to cast this to a numpy array of shape (y,x,3) but am out of my depth when it comes to understanding how to use BytesIO objects.

My current understanding is that this gives a stream of bytes, but may not provide information about how to decode the stream and reconstruct it into my choice data-structure(numpy array).

Is this assumption correct?

Does anyone know how to convert an image format into a numpy array as it’s uploaded.
I’m fine with reformatting all of my pngs to a jpg or whatever before I upload as long as I know how to upload something imagelike.

Here you go, @conic :slightly_smiling_face:

import streamlit as st
import numpy as np
from PIL import Image

img_file_buffer = st.file_uploader('Upload a PNG image', type='png')
if img_file_buffer is not None:
    image = Image.open(img_file_buffer)
    img_array = np.array(image)

Please note that this requires that you have Pillow.

Cheers! :partying_face:

6 Likes

Thanks!

>>> st.balloons()
3 Likes