TypeError: expected str, bytes or os.PathLike object, not PngImageFile In Streamlit web app

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

This is my code and I do not know how to solve this error.please anyone help me regarding this. ERROR:

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:

I loaded the model that I have trained before and made app.py file for web app with the use of streamlit ( Python library) but there is an error regarding image uploading may be I do not know what is is about, Help me in this.

1 Answers

You can deduce the answer using Traceback and documentation of functions you are using. Here is an example.

  • First, see that you get error
TypeError: expected str, bytes or os.PathLike object, not PngImageFile

This means there is issue with the type of object you are passing. Next, see the location, It is here,

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

Look at documentation of this function, it says,

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.
  • Found your mistake ? Let's see what is type of image object ?

  • It is created at

image=Image.open(uploaded_file)

Look at documentation of Image.open(...). What does it say about return type ?

Returns
An Image object.
  • Here's your error, you are passing an image object, whereas function requires Path to the image.
  • That's what interpreter is trying to tell you
TypeError: expected str, bytes or os.PathLike object, not PngImageFile
Related