Image upload problem

Hello community team.
I have a problem with file uploader.
I use file upload to upload images, show that image on the app.
then I use that image as input to my Keras model to make a prediction.
the code was working fine, but now it stopped and get an error message as below

" TypeError: expected str, bytes, or os.PathLike object, not _io.BytesIO " 

my code in details is tw oclasses as below :
1- classify.py

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
from keras.applications.vgg16 import decode_predictions
from keras.applications.vgg16 import VGG16

def predict(image1): 
    model = VGG16()
    image = load_img(image1, target_size=(224, 224))
    # convert the image pixels to a numpy array
    image = img_to_array(image)
    # reshape data for the model
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # prepare the image for the VGG model
    image = preprocess_input(image)
    # predict the probability across all output classes
    yhat = model.predict(image)
    # convert the probabilities to class labels
    label = decode_predictions(yhat)
    # retrieve the most likely result, e.g. highest probability
    label = label[0][0]
    return label 

2- upload.py

import streamlit as st 
from PIL import Image
from classify import predict


st.title("Upload + Classification Example")

uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption='Uploaded Image.', use_column_width=True)
    st.write("")
    st.write("Classifying...")
    label = predict(uploaded_file)
    st.write('%s (%.2f%%)' % (label[1], label[2]*100))

the error in details :

TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO
Traceback:

File "d:\users\bassam\anaconda3\lib\site-packages\streamlit\ScriptRunner.py", line 319, in _run_script
    exec(code, module.__dict__)
File "C:\Users\Bassam\upload.py", line 38, in <module>
    label = predict(uploaded_file)
File "C:\Users\Bassam\classify1.py", line 9, in predict
    image = load_img(image1, target_size=(224, 224))
File "d:\users\bassam\anaconda3\lib\site-packages\keras_preprocessing\image\utils.py", line 113, in load_img    with open(path, 'rb') as f:
1 Like

Hi @BassamAbdeltwab, welcome to the Streamlit community. Please see this thread, which details working with the file_uploader:

Hi, I have the same problem and it was working fine until recently ! something changed with fileuploader but I can’t understand what 

TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO

Traceback:

File "c:\programdata\anaconda3\envs\virtenv\lib\site-packages\streamlit\script_runner.py", line 324, in _run_script
    exec(code, module.__dict__)
File "C:\OpenClassRooms\projet 6\upload.py", line 17, in <module>
    label, probability = predict(uploaded_file)
File "C:\OpenClassRooms\projet 6\classify_120_streamlit.py", line 22, in predict
    image = load_img(image1, target_size=(299, 299))
File "c:\programdata\anaconda3\envs\virtenv\lib\site-packages\tensorflow\python\keras\preprocessing\image.py", line 301, in load_img
    target_size=target_size, interpolation=interpolation)File "c:\programdata\anaconda3\envs\virtenv\lib\site-packages\keras_preprocessing\image\utils.py", line 113, in load_img
    with open(path, 'rb') as f:
1 Like

file_uploader returns a BytesIO buffer, so you need to read the bytes before passing it to another function.

upload = file_uploader(...)

data = upload.read()

This isn’t working, getting the same error while reading images

Hi @sainivedh, As @randyzwitch has already pointed out the file_uploader returns a BytesIO object so you need to wrap it in a TemporaryFile and then feed it to the load_img function.

I have tried this on my system and it works.

from keras.preprocessing.image import load_img

import streamlit as st

from tempfile import NamedTemporaryFile

st.set_option('deprecation.showfileUploaderEncoding', False)

buffer = st.file_uploader("Image here pl0x")
temp_file = NamedTemporaryFile(delete=False)
if buffer:
    temp_file.write(buffer.getvalue())
    st.write(load_img(temp_file.name))

However, I would suggest using PIL directly, check this issue on keras, https://github.com/keras-team/keras/issues/11684
And this comment.
https://github.com/keras-team/keras/issues/11684#issuecomment-440175840

Hope it helps. :slight_smile:

3 Likes

@ash2shukla Have you resolved the problem?
If yes, could you please share the code you have used. I am trying to do image classification, but getting errors in the prediction of uploaded files using st.file_uploader()

just do np.array(file)

Thank you very much. Now the error is resolved.

I have used the PIL directly to upload the image for prediction . But unfortunately getting an error \anaconda3\lib\site-packages\PIL\Image.py", line 546, in getattr
raise AttributeError(name)
AttributeError: read