PyTorch YoloV5使用torch.hub.load与detect.py推理结果不一致问题
YOLOv5两种推理方式结果不一致问题排查及修正
核心问题点
- 图像通道不匹配:OpenCV的
cv2.VideoCapture读取的帧默认是BGR通道顺序,而YOLOv5的detect.py内部会自动将输入转换为RGB格式,你直接将BGR帧传入torch.hub加载的模型,会导致模型识别精度下降,浅色、小尺寸目标(比如案例里的时钟)极易漏检,这是最主要的原因。 - 推理参数未对齐:你只对齐了置信度阈值0.25,但
detect.py默认的iou-thres=0.45、输入推理尺寸--img-size=640等参数你没有在hub加载的模型中显式设置,参数差异会导致NMS过滤结果不同,出现漏检/多检。 - 权重版本不一致:
torch.hub.load('ultralytics/yolov5', 'yolov5s')会默认从官方仓库下载最新版本的yolov5s.pt,如果你本地detect.py用的是旧版本的权重文件,两者权重参数本身存在差异,自然会得到不同的检测结果。
修正后的代码示例
import cv2, torch # 指定加载本地和detect.py一致的权重,避免版本差异 model = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5s.pt') # 对齐所有推理参数 model.conf = 0.25 model.iou = 0.45 model.imgsz = 640 list_of_original_frames = [] list_of_detected_classes_in_all_frames = [] detected_classes = [] check_dict = {} def detect_video(video_path): cap = cv2.VideoCapture(video_path) while (cap.isOpened()): ret, frame = cap.read() if ret == False: break # 核心修正:BGR转RGB,和detect.py输入格式对齐 frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) list_of_original_frames.append(frame_rgb) cap.release() cv2.destroyAllWindows() for file in list_of_original_frames: results = model(file) new_df = results.pandas() new_result = new_df.xywh[0]['name'] list_of_detected_classes_in_all_frames.append(new_result.tolist()) for outer_loop in list_of_detected_classes_in_all_frames: for inner_loop in outer_loop: if inner_loop: detected_classes.append(inner_loop) for iterate in detected_classes: if iterate not in check_dict: check_dict[iterate] = 1 else: check_dict[iterate] = check_dict[iterate] + 1 return check_dict video_path = '/home/hamza/Desktop/House_Video.mp4' check_dict = detect_video(video_path)
内容的提问来源于stack exchange,提问作者Hamza
相关产品推荐
相关产品推荐

