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

YOLOv3口罩检测模型加载报错求助:OpenCV解析weights文件失败

问题解决与模型准确率查看方法

一、解决模型加载解析错误

你遇到的Failed to parse NetParameter file错误,可从以下方向排查修复:

1. 检查文件路径有效性

  • 确认yolov3_custom.cfg和yolov3_custom_4000.weights的实际位置:
    • 若文件和测试脚本在同一目录,直接写文件名即可:
      net = cv2.dnn.readNetFromDarknet('yolov3_custom.cfg', 'yolov3_custom_4000.weights')
      
    • 若用相对路径(如Downloads文件夹),需保证路径指向正确,Windows系统建议用绝对路径:
      net = cv2.dnn.readNetFromDarknet('yolov3_custom.cfg', r'C:\Users\你的用户名\Downloads\yolov3_custom_4000.weights')
      
  • 可先验证路径是否正确:
    import os
    print(os.path.exists('yolov3_custom.cfg'))
    print(os.path.exists(r'Downloads\yolov3_custom_4000.weights'))
    

2. 确认文件未损坏

对比Colab中训练生成的weights文件大小与本地下载的文件大小,若不一致,重新下载(建议用浏览器直接下载,避免中断)。

3. 保证cfg与weights文件匹配

训练时使用的yolov3_custom.cfg必须和测试时完全一致:

  • 检查cfg文件中[yolo]层的classes值是否为2(对应你的两类检测),filters值是否为(2+5)*3=21,训练时修改过的cfg不能随意替换。

4. 调整OpenCV加载方式或版本

  • 尝试换用readNet方法并指定框架:
    net = cv2.dnn.readNet('yolov3_custom_4000.weights', 'yolov3_custom.cfg', 'darknet')
    
  • 若为版本兼容问题,升级到最新稳定版:
    pip install --upgrade opencv-python opencv-contrib-python
    

代码冗余优化

你的测试代码存在重复的检测逻辑,可简化为一次检测后执行NMS:

boxes =[]
confidences = []
class_ids = []

for output in layerOutputs:
    for detection in output:
        score = detection[5:]
        class_id = np.argmax(score)
        confidence = score[class_id]
        if confidence > 0.5:  # 统一置信度阈值
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * hight)
            w = int(detection[2] * width)
            h = int(detection[3]* hight)
            x = int(center_x - w/2)
            y = int(center_y - h/2)
            boxes.append([x,y,w,h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

# 仅执行一次NMS
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.8, 0.4)

二、查看模型准确率

1. 查看训练日志

Colab训练时,Darknet会生成train.log文件,里面包含每轮训练的mAP(平均精度均值)、precision(精确率)、recall(召回率)等指标,直接查看该日志即可。

2. 用Darknet验证命令生成结果

在Colab中运行验证命令,针对验证集计算准确率:

./darknet detector valid data/obj.data cfg/yolov3_custom.cfg backups/yolov3_custom_4000.weights

执行后会在results文件夹下生成每个类别的精度结果,以及整体的mAP值。

3. 自定义代码计算准确率

若需本地计算,可编写代码遍历验证集:

  1. 读取每张验证集图片和对应的标注框(格式通常为class_id x_center y_center width height);
  2. 用模型对图片检测,得到预测框;
  3. 计算预测框与真实框的IOU(交并比),设定阈值(如0.5)判断TP、FP、FN;
  4. 基于统计结果计算精确率、召回率和mAP。

内容的提问来源于stack exchange,提问作者SoManyBugssssss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:45:34