You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenCV 4.6.0 DNN加载YOLOv7-onnx模型报错,能否正常加载?

能否用OpenCV加载YOLOv7?

可以,但你遇到的错误是因为OpenCV 4.6.0的dnn模块对YOLOv7模型里的NonMaxSuppression层支持不完善。解决方法有两种:

方案一:升级OpenCV版本

将OpenCV升级到4.7.0及以上版本,这些版本修复了ONNX模型中NonMaxSuppression层的解析问题,能直接加载yolov7-nms-640.onnx这类带NMS的模型。

方案二:使用不带NMS的YOLOv7模型并自行实现NMS

如果无法升级OpenCV,可使用官方仓库导出的不带NMS的YOLOv7 ONNX模型,推理后手动实现非极大值抑制(NMS)来过滤检测结果。示例代码逻辑如下:

import cv2
import numpy as np

# 加载不带NMS的YOLOv7模型
net = cv2.dnn.readNetFromONNX("yolov7-640.onnx")
image = cv2.imread("test.jpg")
h, w = image.shape[:2]

# 预处理图像
blob = cv2.dnn.blobFromImage(image, 1/255.0, (640, 640), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward()

# 解析输出并调用OpenCV内置NMS
boxes = []
scores = []
# 根据YOLOv7输出格式提取边界框和置信度(需适配模型输出维度)
for out in outputs:
    for detection in out:
        scores.append(detection[4])
        box = detection[0:4] * np.array([w, h, w, h])
        (centerX, centerY, width, height) = box.astype("int")
        x = int(centerX - (width / 2))
        y = int(centerY - (height / 2))
        boxes.append([x, y, int(width), int(height)])

# 执行NMS
indices = cv2.dnn.NMSBoxes(boxes, scores, 0.25, 0.45)

# 绘制检测结果
if len(indices) > 0:
    for i in indices.flatten():
        (x, y) = (boxes[i][0], boxes[i][1])
        (w_box, h_box) = (boxes[i][2], boxes[i][3])
        cv2.rectangle(image, (x, y), (x + w_box, y + h_box), (0, 255, 0), 2)
        text = f"{scores[i]:.2f}"
        cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

cv2.imshow("YOLOv7 Detection", image)
cv2.waitKey(0)

内容的提问来源于stack exchange,提问作者Ajesh Mon R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:45:41