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

YOLO自定义模型检测异常:仅输出-1问题排查求助

问题排查与修复方案

核心问题分析

你的代码始终输出-1,说明没有检测到任何目标,结合代码和描述,主要有以下几个问题:

1. 模型文件名不匹配

你提到自己的模型是best.pt,但代码中加载的是bestall5.pt:

model = YOLO("bestall5.pt")

这会导致加载错误的模型(或不存在的模型),自然无法检测到目标。

2. 检测结果遍历逻辑错误

Ultralytics YOLO返回的results_list是包含单个Results对象的列表,而Results对象的xyxy属性是一个列表,每个元素对应单帧的检测框张量。你当前的遍历方式没有正确访问到检测框数据,导致漏检。

3. Class ID类型处理不当

直接通过result.tolist()获取的class_id是浮点数类型(比如0.0或1.0),而model.names的键是整数,这会导致无法正确匹配类名,进而无法标记目标已检测。

修复后的完整代码

import cv2
from ultralytics import YOLO

video_path = 'data/video1.mp4'
video_out_path = 'out.mp4'

cap = cv2.VideoCapture(video_path)

if not cap.isOpened():
    print("Error: Could not open the video file.")
    exit()

ret, frame = cap.read()

if not ret:
    print("Error: Could not read the first frame from the video.")
    exit()

cap_out = cv2.VideoWriter(video_out_path, cv2.VideoWriter_fourcc(*'MP4V'), cap.get(cv2.CAP_PROP_FPS),
                          (int(cap.get(3)), int(cap.get(4))))

# 修正模型文件名
model = YOLO("best.pt")

detection_threshold = 0.5
while ret:
    results_list = model(frame)

    headlight_detected = False
    person_detected = False

    # 遍历结果(单帧对应一个Results对象)
    for results in results_list:
        # 使用boxes属性更规范地处理检测框
        boxes = results.boxes
        for box in boxes:
            # 获取置信度并判断阈值
            score = box.conf[0].item()
            if score < detection_threshold:
                continue
            
            # 获取类别ID并转为整数
            class_id = int(box.cls[0].item())
            class_name = model.names[class_id]

            if class_name == "headlight":
                headlight_detected = True
            elif class_name == "person":
                person_detected = True

    # 按规则输出结果
    if headlight_detected:
        output = 0
    elif person_detected:
        output = 1
    else:
        output = -1

    print("Output:", output)

    cap_out.write(frame)
    cv2.imshow('Object Detection', frame)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    ret, frame = cap.read()

cap.release()
cap_out.release()
cv2.destroyAllWindows()

额外优化说明

  • 使用results.boxes替代直接访问xyxy,这是Ultralytics官方推荐的检测框处理方式,更稳定且易于维护。
  • 先判断置信度是否达标,再处理类别匹配,避免无效计算。
  • 简化了输出条件:只要检测到车灯(无论是否有行人)都返回0,逻辑更简洁,和你要求的规则完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:40:26