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

使用YOLOv5调用摄像头目标检测时遭遇segmentation fault错误的排查

问题分析与修复方案

可能的错误点及修复步骤

1. 未检查摄像头帧读取状态

摄像头初始化失败或临时读取异常时,cam.read()返回的ret为False,此时frame是None,后续对frame的切片操作会直接触发段错误。

修复:在处理帧前先判断ret,跳过无效帧:

while(True): 
    ret, frame = cam.read()
    if not ret:
        print("无法读取摄像头帧,重试")
        continue

2. 冗余且易出错的颜色转换操作

代码中存在无意义的颜色格式来回转换:

frame = frame[:, :, [2,1,0]]  # BGR转RGB
frame = Image.fromarray(frame) 
frame = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)  # 又转回BGR

这不仅浪费资源,还可能在类型转换过程中引发内存错误,直接删除这段代码即可——YOLOv5模型可以直接处理OpenCV读取的BGR格式帧。

3. 依赖库版本或加载方式问题

段错误也可能源于依赖库版本不兼容:

  • 建议使用官方推荐的方式安装YOLOv5,替代torch.hub.load,避免版本冲突:
    pip install yolov5
    
    加载模型时改用本地导入:
    from yolov5 import YOLO
    model = YOLO('yolov5s.pt')
    
  • 检查OpenCV版本,建议使用4.x系列,避免与PyTorch的CUDA版本冲突;若用CPU运行,确保OpenCV编译支持CPU。
  • 确认摄像头权限:Linux/macOS下,确保当前用户有权限访问/dev/video0,可执行以下命令添加权限:
    sudo usermod -aG video $USER
    

修复后的完整代码

def object_detector():
    DEVICE = "cuda" if torch.cuda.is_available() else "cpu" 
    from yolov5 import YOLO
    model = YOLO('yolov5s.pt')
    model.to(DEVICE)  # 显式指定运行设备

    cam = cv2.VideoCapture(0)
    # 提前检查摄像头是否成功打开
    if not cam.isOpened():
        print("无法打开摄像头")
        return
    
    while(True): 
        ret, frame = cam.read()
        if not ret:
            print("读取帧失败,重试...")
            continue

        result = model(frame, size=640)
        cv2.imshow('YOLO', np.squeeze(result.render()))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cam.release()
    cv2.destroyAllWindows()

内容的提问来源于stack exchange,提问作者e.iluf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:50:25