opencv 使用“net = cv2.dnn.readNet(“yolov7.onnx”)“阅读onnx文件时出现问题,如何解决此问题

cnjp1d6j  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(1063)

这是我得到的错误。我试图使用这个repo -https://github.com/WongKinYiu/yolov7来实现yolov 7对象检测代码
我得到了yolov7.pt的重量文件,这是预先训练好的模型。
并使用此https://github.com/WongKinYiu/yolov7/blob/u5/export.py将.pt转换为.onnx
之后,我使用输入为.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()

我使用了Google Collab。它有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'

而不是分享一些随机解决的问题的网址可以有人好心地指导我到底我应该做什么。我是非常新的,并一直在谷歌两天来解决这个错误[yolov 5有同样的问题,但解决方案是改变 Torch 版本为1.11,我尝试了,并没有为我工作]注-我使用yolov 7

xdnvmnnf

xdnvmnnf1#

下面是一个示例解决方案,可能对您有所帮助
在下面的代码中,我通过加载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)

"希望能有所帮助"

相关问题