将使用 Streamlit 上传的图像转换为 numpy 数组
Posted
技术标签:
【中文标题】将使用 Streamlit 上传的图像转换为 numpy 数组【英文标题】:Turning an image uploaded using Streamlit to a numpy array 【发布时间】:2021-11-26 02:30:18 【问题描述】:我正在使用 Streamlit 为机器学习项目开发一个 web 应用程序。
我在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】:来自Streamlit documentation for 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 对象,然后可以将其转换为表示图像的数组。
【讨论】:
以上是关于将使用 Streamlit 上传的图像转换为 numpy 数组的主要内容,如果未能解决你的问题,请参考以下文章
上传图像多部分表单 HTTPWebRequest - 将图像数据转换为字符串?
如何将 <class 'streamlit.uploaded_file_manager.UploadedFile'> 类型的文件转换为 Ptr<cv::UMat>?