在opencv python中加载YOLOv5时出错,如何解决?

1tuwyuhd  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(718)

我正在用YOLOv5在opencv中运行人物检测,但是在加载模型时遇到了问题。我的opencv版本是4.6.0,按照这个链接的教程,我写了以下代码

# hyper parameters
INPUT_WIDTH = 640  # width of the input for the YOLOv5 network
INPUT_HEIGHT = 640  # height of the  input for the YOLOv5 network
SCORE_THRESHOLD = 0.5  # filter low probability classes
NMS_THRESHOLD = 0.45  # remove overlapping bounding boxes (?)
CONFIDENCE_THRESHOLD = 0.45  # filter low probability detection
BLACK = (0, 0, 0)
BLUE = (255, 178, 50)
YELLOW = (0, 255, 255)
classes = []
person_found = False
# taking classes names
class_files = 'yolo/coco.names'
with open(class_files, 'r') as source:
classes = source.read().rstrip('\n').split('\n')
# weights path
weights = 'yolo/models/yolov5s.onnx'
net = cv2.dnn.readNet(weights)
# parameters: image, scale factor, size in form of tuple, mean subtraction, swapRB
blob = cv2.dnn.blobFromImage(frame, scalefactor=1/255, size=(INPUT_WIDTH, INPUT_HEIGHT), mean=[0, 0, 0], swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(net.getUnconnectedOutLayersNames())

但是当我试图加载模型时,我得到了这个错误:

[ERROR:0@1.622] global D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\onnx\onnx_importer.cpp (1021) cv::dnn::dnn4_v20220524::ONNXImporter::handleNode DNN/ONNX: ERROR during processing node with 1 inputs and 1 outputs: [Identity]:(onnx_node!Identity_0) from domain='ai.onnx'
Traceback (most recent call last):
  File "D:\Unitn\Corsi\Computer vision\project\synopsis\main.py", line 25, in <module>
    bg_frames = find_bg_frames(video, duration, fps)
  File "D:\Unitn\Corsi\Computer vision\project\synopsis\utils.py", line 152, in find_bg_frames
    people_found = find_people_with_yolo(frame)
  File "D:\Unitn\Corsi\Computer vision\project\synopsis\utils.py", line 102, in find_people_with_yolo
    net = cv2.dnn.readNetFromONNX(weights)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\onnx\onnx_importer.cpp:1040: error: (-2:Unspecified error) in function 'cv::dnn::dnn4_v20220524::ONNXImporter::handleNode'
> Node [Identity@ai.onnx]:(onnx_node!Identity_0) parse error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\layer.cpp:246: error: (-215:Assertion failed) inputs.size() in function 'cv::dnn::dnn4_v20220524::Layer::getMemoryShapes'
>

谁能帮我找出问题所在?

u0njafvf

u0njafvf1#

仔细看一下outputs的形状,发现它是[1,3,80,80,85]。然而,对于默认的640x640 onnx导出,它应该是[25200x85]。这似乎是一个错误的从PyTorch到ONNX的转换。在yolov5s.onnx模型中,已经在article中更新了。
另外,torch==1.12有一些bug,在修正之前,请在转换模型时使用torch==1.11。
在GitHub上查看此问题。

5vf7fwbs

5vf7fwbs2#

我遇到了同样的问题,我通过为导出添加“--simplify”解决了该问题

相关问题