gpt4 book ai didi

streamlit - 无法加载图像并将其传递给模型预测的预处理

转载 作者:行者123 更新时间:2023-12-05 04:20:14 28 4
gpt4 key购买 nike

我正在尝试从同一目录中的本地系统上传图像。上传后,当我通过打开的 cv 拆分和合并 b、g 和 r 颜色时,我收到错误 ValueError:没有足够的值来解压(预期 3,得到 0)

错误:

这是显示的错误是否有可能在我可以跟踪不同代码行更改的流中进行调试? (如在图像路径中一样)当在 google collab 中执行时,作为单个 ipynb 文件正常运行并且我得到所需的分类

ValueError: not enough values to unpack (expected 3, got 0)
Traceback:
File "C:\Users\ADARSH\anaconda3\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 564, in _run_script
exec(code, module.__dict__)
File "C:\Users\ADARSH\streamlit\deploy_test.py", line 76, in <module>
main()
File "C:\Users\ADARSH\streamlit\deploy_test.py", line 68, in main
mask = imageToTensor('image')
File "C:\Users\ADARSH\streamlit\deploy_test.py", line 44, in imageToTensor
b,g,r = cv2.split(bgr_img)

我的整个 streamlit 应用程序代码

from pathlib import Path
import cv2
import numpy as np
import pandas as pd
import os
import cv2
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
from sklearn.utils import shuffle
from tqdm import tqdm_notebook

import streamlit as st

from PIL import Image as impo



from fastai import *
from fastai.vision import *
from torchvision.models import *




class MyImageItemList(ImageList):
def open(self, fn:PathOrStr)->Image:
img = readCroppedImage(fn.replace('/./','').replace('//','/'))
# This ndarray image has to be converted to tensor before passing on as fastai Image, we can use pil2tensor
return vision.Image(px=pil2tensor(img, np.float32))


def read_image(name):
image = st.file_uploader("Upload an "+ name, type=["png", "jpg", "jpeg",'tif'])
if image is not None:
im = impo.open(image)
im.filename = image.name
return image


def imageToTensor(image):
sz = 68
bgr_img = cv2.imread(image)
b,g,r = cv2.split(bgr_img)
rgb_img = cv2.merge([r,g,b])
# crop to center to the correct size and convert from 0-255 range to 0-1 range
H,W,C = rgb_img.shape
rgb_img = rgb_img[(H-sz)//2:(sz +(H-sz)//2),(H-sz)//2:(sz +(H-sz)//2),:] / 256
return vision.Image(px=pil2tensor(rgb_img, np.float32))


def learn_infernce():
return load_learner('./')


def get_prediction(image):
if st.button('Classify'):
pred, pred_idx, probs = learn_inference.predict(image)
classes = ['negative', 'tumor']
st.write(f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}')
else:
st.write(f'Click the button to classify')


def main():
st.set_page_config(page_title='Cancer detection', page_icon=None, layout='centered', initial_sidebar_state='auto')
image = read_image('image')
mask = imageToTensor('image')
if mask is not None:
get_prediction('mask')




if __name__ == "__main__":
main()

最佳答案

在您的主要函数中,您传递的是“str”而不是变量,而且我认为您的 read_image 结构不合理。

你应该做的是首先将上传的文件保存在一个目录中,然后从该目录中获取文件并将其作为参数传递给 imageToTensor()。这是一种解决方法,可以让您完全控制文件。否则,在修复第一个错误后,您将收到其他错误消息。

您可以在一个单独的 python 文件中自动执行几行代码,以在给定的持续时间内从目录中删除上传的文件。

注意:请注意导入,因为我跳过了它们以保持代码简短

class MyImageItemList(ImageList):
def open(self, fn:PathOrStr)->Image:
img = readCroppedImage(fn.replace('/./','').replace('//','/'))
# This ndarray image has to be converted to tensor before passing on as fastai Image, we can use pil2tensor
return vision.Image(px=pil2tensor(img, np.float32))


# Refactured read_image()
def get_uploaded_image():
upload = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg",'tif'])

if upload is not None:
st.write(upload.name)

# Create a directory and save the image file before proceeding.
file_path = os.path.join("data/uploadedImages/", upload.name)
with open(file_path, "wb") as user_file:
user_file.write(upload.getbuffer())

return file_path # fixed indentation


def imageToTensor(image):
sz = 68
bgr_img = cv2.imread(image)
b,g,r = cv2.split(bgr_img)
rgb_img = cv2.merge([r,g,b])

# crop to center to the correct size and convert from 0-255 range to 0-1 range
H,W,C = rgb_img.shape
rgb_img = rgb_img[(H-sz)//2:(sz +(H-sz)//2),(H-sz)//2:(sz +(H-sz)//2),:] / 256

return vision.Image(px=pil2tensor(rgb_img, np.float32))


def learn_infernce():
return load_learner('./')


def get_prediction(image):

if st.button('Classify'):
pred, pred_idx, probs = learn_inference.predict(image)
classes = ['negative', 'tumor']
st.write(f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}')
else:
st.write(f'Click the button to classify')


def main():
st.set_page_config(page_title='Cancer detection', page_icon=None, layout='centered', initial_sidebar_state='auto')

# Holds the saved file path
user_image = get_uploaded_image()

if user_image is not None:
# Pass the path to imageToTensor() as a parameter.
mask = imageToTensor(user_image)
get_prediction(mask)




if __name__ == "__main__":
main()

输出: enter image description here

关于streamlit - 无法加载图像并将其传递给模型预测的预处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74569805/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com