Reputation: 1291
I'm writing some code for the Streamlit app, where I want the user to upload a .jpg image file and it gives me this error, "UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x00000293778F98B0>"
My code is as follows:
import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
st.title("Image classification Web App")
# loading images
def load_image(image):
image = image.resize((224,224))
im_array = np.array(image)/255 # a normalised 2D array
im_array = im_array.reshape(-1, 224, 224, 3) # to shape as (1, 224, 224, 3)
return im_array
...
if st.button("Try with the Default Image"):
image=load_image(Image.open('C:/Users/.../image21.jpg'))
st.subheader("Human is detected")
st.image(image)
st.image(initialize_model(model_name, image))
st.subheader("Upload an image file")
uploaded_file = st.file_uploader("Upload a JPG image file", type=["jpg", "jpeg"])
if uploaded_file:
image = load_image(Image.open(uploaded_file))
st.image(initialize_model(model_name, image))
However, I have no problem uploading an image with this line,
st.image(Image.open('C:/Users/../image21.jpg'))
Can anyone advise me whats wrong here?
Thanks.
Upvotes: 1
Views: 1057
Reputation: 5721
You got that error because uploaded files in streamlit are file-like
objects meaning they are not actual files. To Solve this problem, you will have to save the uploaded file to local directory, fetch the file from that directory and proceed with the rest of execution. This method gives you a total control of the file.
I will recommend you create a new function to accept and save user inputs. And after saving, return the path of the saved file, then read from that path, when that is successful, pass the file as a second argument to initialize_model
.
Example:
import os
def get_user_input():
st.subheader("Upload an image file")
uploaded_file = st.file_uploader("Upload a JPG image file", type=["jpg", "jpeg"])
if uploaded_file is not None:
user_file_path = os.path.join("users_uploads/", uploaded_file.name)
with open(user_file_path, "wb") as user_file:
user_file.write(uploaded_file.getbuffer())
return user_file_path
uploaded_file = get_user_input()
if uploaded_file is not None:
image = load_image(uploaded_file)
st.image(initialize_model(model_name, image))
Upvotes: 0