我在使用 'net = cv2.dnn.readNet("yolov7.onnx")' 读取 onnx 文件时遇到问题。如何解决这个问题

问题描述 投票:0回答:1

这是我收到的错误。我试图使用此存储库实现 yolov7 对象检测代码 - https://github.com/WongKinYiu/yolov7

我得到了yolov7.pt权重文件,这是预训练的模型。

并使用此将 .pt 转换为 .onnx https://github.com/WongKinYiu/yolov7/blob/u5/export.py

之后我使用了对象检测代码,输入为 .onnx 权重文件。

import os, time
import cv2
import matplotlib.pyplot as plt

coco_classes = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
        'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
        'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
        'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
        'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
        'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
        'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
        'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
        'hair drier', 'toothbrush']

# net = cv2.dnn.readNet("yolov7.onnx")
net = cv2.dnn.readNet("/content/1-yolov7.onnx")
model = cv2.dnn_DetectionModel(net)
model.setInputParams(size=(416, 416), scale=1 / 255, swapRB=True)

path = './testimg/'

for fn in os.listdir(path):
    image = cv2.imread(path + fn)

    t = time.time()
    c, v, b = model.detect(image, 0.2, 0.4)
    t = time.time() - t

    c = [coco_classes[x] for x in c]

    for (classid, score, box) in zip(c, v, b):
        if classid == 0 or classid == 2:
            lx, ly, cw, ch = box
        x=cv2.rectangle(image, box, (255, 0, 255), 3)
    plt.imshow(cv2.cvtColor(x, cv2.COLOR_BGR2RGB))
    plt.waitforbuttonpress()

我使用了谷歌协作。它有OpenCV 4.6.0,pytorch版本是1.12,我也尝试使用pytorch 1.11,但它没有解决问题

错误--

    yolov7_detector = YOLOv7(args.modelpath, conf_thres=args.confThreshold, iou_thres=args.nmsThreshold)
  File "F:/REPO/code/yolov7-u5/detect.py", line 13, in __init__
    self.net = cv2.dnn.readNet(path)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\onnx\onnx_importer.cpp:255: error: (-5:Bad argument) Can't read ONNX file: models/yolov7_640x640.onnx in function 'cv::dnn::dnn4_v20220524::ONNXImporter::ONNXImporter'

不要分享一些随机解决的问题 URL,有人可以准确地指导我应该做什么。我对此很陌生,已经用谷歌搜索了两天来解决这个错误[yolov5有同样的问题,但解决方案是将火炬版本更改为1.11,我尝试过但对我不起作用]注意-我正在使用yolov7

python opencv object-detection yolo
1个回答
0
投票

这是一个示例解决方案,可能会对您有所帮助

在下面的代码中,我通过加载 yolov7 预训练模型来检测图像中的人

import torch
import os
import cv2
import matplotlib.pyplot as plt
import glob

# Load fine-tuned custom model
model = torch.hub.load('WongKinYiu/yolov7', 'custom', 'model_path/yolov7.pt',
                        force_reload=True, trust_repo=True)


PERSON_CONFIDENCE = 0.50
OUTPUT_DIR = 'output'

image_path_ = glob.glob('person_det_results/input_videos/all_in_one/frames/*')
out_path = 'person_det_results/input_videos/all_in_one/all_in_one_person_imgs'

os.makedirs(OUTPUT_DIR, exist_ok=True)
c = 1
# Run the Inference and draw predicted bboxes
for image_path in image_path_:
    results = model(image_path)
    df = results.pandas().xyxy[0]
    image = cv2.imread(image_path)
    for i, row in df.iterrows():
        if row['class'] == 0 and row['confidence'] > PERSON_CONFIDENCE:
            person_bbox = [int(row['xmin']), int(row['ymin']), int(row['xmax']), int(row['ymax'])]
            person_image = image[person_bbox[1]:person_bbox[3], person_bbox[0]:person_bbox[2]]
            cv2.imwrite(f'{out_path}/{c}_person.jpg', person_image)
            c+=1
            
print('Done..',c)
     

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.