如何将 <class 'streamlit.uploaded_file_manager.UploadedFile'> 类型的文件转换为 Ptr<cv::UMat>?
Posted
技术标签:
【中文标题】如何将 <class \'streamlit.uploaded_file_manager.UploadedFile\'> 类型的文件转换为 Ptr<cv::UMat>?【英文标题】:How to convert a file of type <class 'streamlit.uploaded_file_manager.UploadedFile'> to Ptr<cv::UMat>?如何将 <class 'streamlit.uploaded_file_manager.UploadedFile'> 类型的文件转换为 Ptr<cv::UMat>? 【发布时间】:2021-08-07 10:15:33 【问题描述】:我想要做的是通过 Streamlit file_uploader 上传一个文件,然后将该 png 传递给一个函数进行预测。这是我的代码的样子:
if choice == "Upload Image":
image_file = st.sidebar.file_uploader('Upload an image', type = 'png')
if image_file and st.sidebar.button('Load'):
image = get_opened_image(image_file)
with st.beta_expander('Selected Image', expanded=True):
st.image(image, use_column_width=True)
prediction = image_pred(image_file) # line 52
st.subheader("Prediction")
st.markdown(f'The predicted label is: **prediction**')
这是调用的预测函数:
def image_pred(filename):
emo = []
model = model_from_json(open("fer.json", "r").read())
model.load_weights('fer.h5')
emotion_dict = 0: "Not Engaged", 1: "Not Engaged", 2: "Nominally Engaged", 3: "Very Engaged", 4: "Not Engaged",
5: "Very Engaged", 6: "Nominally Engaged"
facecasc = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(filename, cv2.COLOR_BGR2GRAY) # line 29 error here
faces = facecasc.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
这是我得到的错误:
TypeError: Expected Ptr<cv::UMat> for argument 'src'
line 52, in <module>
prediction = image_pred(image_file)
line 29, in image_pred
gray = cv2.cvtColor(filename, cv2.COLOR_BGR2GRAY)
如何将上传的文件转换为可以作为 src 传递给 cv2.cvtColor() 的合适格式?提前致谢
【问题讨论】:
【参考方案1】:cv2.cvtColor()
需要图像数据作为第一个参数,而不是文件名。你可以这样得到:
image = cv2.imread(filename)
# now convert the color space
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
【讨论】:
以上是关于如何将 <class 'streamlit.uploaded_file_manager.UploadedFile'> 类型的文件转换为 Ptr<cv::UMat>?的主要内容,如果未能解决你的问题,请参考以下文章