【问题标题】:UnidentifiedImageError: cannot identify image file when running StreamlitUnidentifiedImageError:运行 Streamlit 时无法识别图像文件
【发布时间】:2022-12-17 20:44:06
【问题描述】:

我正在为 Streamlit 应用程序编写一些代码,我希望用户在其中上传一个 .jpg 图像文件,它给了我这个错误,“UnidentifiedImageError:无法识别图像文件 <_io.BytesIO object at 0x00000293778F98B0>”

我的代码如下:

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))

但是,我用这条线上传图片没问题,

st.image(Image.open('C:/Users/../image21.jpg'))

谁能告诉我这里出了什么问题?

谢谢。

【问题讨论】:

    标签: image image-processing python-imaging-library streamlit


    【解决方案1】:

    您收到该错误是因为在 streamlit 中上传的文件是 file-like 对象,这意味着它们不是实际文件。要解决此问题,您必须将上传的文件保存到本地目录,从该目录中获取文件并继续执行其余部分。此方法使您可以完全控制文件。

    我会建议您创建一个新函数来接受和保存用户输入。保存后,返回保存文件的路径,然后从该路径读取,成功后,将文件作为第二个参数传递给initialize_model

    例子:

    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))
    

    【讨论】:

    • 不幸的是,它没有帮助。我用过 def load_image(uploaded_file)。谢谢你的尝试。
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2021-12-28
    • 1970-01-01
    • 2020-05-26
    • 2017-09-11
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多