Преобразование изображения, загруженного с помощью Streamlit, в массив numpy

#tensorflow #machine-learning #keras #streamlit

Вопрос:

Я работаю над веб-приложением для проекта машинного обучения с использованием Streamlit.

Я столкнулся с этой ошибкой в load_img :

 TypeError: expected str, bytes or os.PathLike object, not UploadedFile.
 
 from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.applications.vgg16 import decode_predictions
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import model_from_json
import numpy as np
import cv2
import tensorflow as tf
import streamlit as st


st.write("This is a simple image classification web app to identify cars")
file = st.file_uploader("Please upload an image file", type=["jpg", "png"])


def import_and_predict(image_data, model):

        image = load_img(image_data,target_size=(64,64))  

        img = img_to_array(image)

        img = np.array(image) 
        img = img / 255.0
        image = img.resize((64,64))

        img = img.reshape(1,64,64,3)
        label = model.predict_classes(img)
    
        prediction = label[0][0]
        
        return f"Prediction: {prediction}" 

if file is None:
    st.text("Please upload an image file")
else:
    import_and_predict(file, model)
 

Ответ №1:

Из потоковой документации для file_uploader :

 >>> uploaded_file = st.file_uploader("Choose a file")
>>> if uploaded_file is not None:
...     # To read file as bytes:
...     bytes_data = uploaded_file.getvalue()
...     st.write(bytes_data)
 

Приведенный выше код предоставит вам объект BytesIO, который затем может быть преобразован в массив, представляющий изображение.