TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 Streamlit Web 应用程序中的 PngImageFile

Posted

技术标签:

【中文标题】TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 Streamlit Web 应用程序中的 PngImageFile【英文标题】:TypeError: expected str, bytes or os.PathLike object, not PngImageFile In Streamlit web app 【发布时间】:2021-07-19 02:18:59 【问题描述】:
import streamlit as st 
from PIL import Image 
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import numpy as np
import tensorflow as tf
from pathlib import Path

@st.cache(allow_output_mutation=True)
def get_model():
        model = load_model('TSR.hdf5')
        print('Model Loaded')
        return model 

sign_names = 
        0: 'Speed limit (20km/h)',
        1: 'Speed limit (30km/h)',
        2: 'Speed limit (50km/h)',
        3: 'Speed limit (60km/h)',
        4: 'Speed limit (70km/h)',
        5: 'Speed limit (80km/h)',
        6: 'End of speed limit (80km/h)',
        7: 'Speed limit (100km/h)',
        8: 'Speed limit (120km/h)',
        9: 'No passing',
        10: 'No passing for vehicles over 3.5 metric tons',
        11: 'Right-of-way at the next intersection',
        12: 'Priority road',
        13: 'Yield',
        14: 'Stop',
        15: 'No vehicles',
        16: 'Vehicles over 3.5 metric tons prohibited',
        17: 'No entry',
        18: 'General caution',
        19: 'Dangerous curve to the left',
        20: 'Dangerous curve to the right',
        21: 'Double curve',
        22: 'Bumpy road',
        23: 'Slippery road',
        24: 'Road narrows on the right',
        25: 'Road work',
        26: 'Traffic signals',
        27: 'Pedestrians',
        28: 'Children crossing',
        29: 'Bicycles crossing',
        30: 'Beware of ice/snow',
        31: 'Wild animals crossing',
        32: 'End of all speed and passing limits',
        33: 'Turn right ahead',
        34: 'Turn left ahead',
        35: 'Ahead only',
       

def predict(image):
        loaded_model = get_model()
        image = load_img(image, target_size=(30,30), color_mode = "grayscale")
        image = img_to_array(image)
        image = image/255.0
        image = np.reshape(image,[1,30,30,1])
        classes = loaded_model.predict_classes(image)
        return classes

st.title("Traffic Sign Classifier")
uploaded_file = st.file_uploader("Choose an image...", type="png")

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("Result...")
        label = predict(image)
        label = label.item()
        res = sign_names.get(label)
        st.markdown(res)

这是我的代码,我不知道如何解决这个错误。请任何人帮助我解决这个问题。 错误:

TypeError: expected str, bytes or os.PathLike object, not PngImageFile
Traceback:
File "c:\users\kruna\appdata\local\programs\python\python39\lib\site-packages\streamlit\script_runner.py", line 333, in _run_script
    exec(code, module.__dict__)
File "K:\TrafficSignUpload\app.py", line 73, in <module>
    label = predict(image)
File "K:\TrafficSignUpload\app.py", line 57, in predict
    image = load_img(image, target_size=(30,30), color_mode = "grayscale")
File "C:\Users\kruna\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\keras\preprocessing\image.py", line 295, in load_img
    return image.load_img(path, grayscale=grayscale, color_mode=color_mode,
File "C:\Users\kruna\AppData\Roaming\Python\Python39\site-packages\keras_preprocessing\image\utils.py", line 113, in load_img
    with open(path, 'rb') as f:

我加载了我之前训练过的模型,并使用 streamlit(Python 库)为 web 应用程序制作了 app.py 文件,但是关于图像上传的错误可能是我不知道是关于什么的,帮助我在里面。

【问题讨论】:

【参考方案1】:

您可以使用 Traceback 和您正在使用的函数的文档来推断答案。这是一个例子。

首先,看看你得到错误
TypeError: expected str, bytes or os.PathLike object, not PngImageFile

这意味着您传递的对象类型存在问题。 接下来,看位置,就在这里,

image = load_img(image, target_size=(30,30), color_mode = "grayscale")

看看这个function的文档,上面写着,

Arguments
path    Path to image file.

grayscale   DEPRECATED use color_mode="grayscale".

color_mode  One of "grayscale", "rgb", "rgba". Default: "rgb". The desired image format.

target_size Either None (default to original size) or tuple of ints (img_height, img_width).

interpolation   Interpolation method used to resample the image if the target size is different from that of the loaded image. Supported methods are "nearest", "bilinear", and "bicubic". If PIL version 1.1.3 or newer is installed, "lanczos" is also supported. If PIL version 3.4.0 or newer is installed, "box" and "hamming" are also supported. By default, "nearest" is used.

发现你的错误了吗? 让我们看看图像对象的类型是什么?

创建于

image=Image.open(uploaded_file)

查看documentation 的Image.open(...)。它说明了返回类型是什么?

Returns
An Image object.
这是您的错误,您正在传递一个图像对象,而函数需要图像的路径。 这就是口译员试图告诉您的内容
TypeError: expected str, bytes or os.PathLike object, not PngImageFile

【讨论】:

以上是关于TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 Streamlit Web 应用程序中的 PngImageFile的主要内容,如果未能解决你的问题,请参考以下文章

Fastparquet 在使用 dataframe.to_parquet() 时给出“TypeError:预期的 str、字节或 os.PathLike 对象,而不是 _io.BytesIO”

发送图像时预期的 str、bytes 或 os.PathLike 对象,而不是 numpy.ndarray

python3报错:TypeError: can't concat bytes to str

builtins.TypeError:必须是 str,而不是 bytes

Python 3.8 TypeError: can't concat str to bytes - TypeError: a bytes-like object is required, not 's

python TypeError: must be str, not bytes错误