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

使用OpenCV读取摄像头帧时触发Assertion failed错误求助

YOLOv5自定义模型摄像头目标检测报错修复

问题描述

尝试使用YOLOv5自定义.pt模型通过摄像头进行目标检测,运行以下Python代码:

# Importamos librerias
import torch
import cv2
import numpy as np
import pandas

# Leemos el modelo
model = torch.hub.load('ultralytics/yolov5', 'custom',
                       path = 'C:/Users/maxim/OneDrive/Documentos/jupyterbooks/detector.pt')

# Realizo Videocaptura
cap = cv2.VideoCapture(1)

# Empezamos
while True:
    # Realizamos lectura de frames
    ret, frame = cap.read()

    # Correccion de color
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # Realizamos las detecciones
    detect = model(frame)
    
    # Mostramos FPS
    cv2.imshow('Detector de Figuras', np.squeeze(detect.render()))

    # Leemos el teclado
    t = cv2.waitKey(5)
    if t == 27:
        break

cap.release()
cv2.destroyAllWindows()

运行后出现错误:

error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

错误原因

这个错误的核心是cv2.cvtColor函数接收的frame为空,说明cap.read()没有成功读取到摄像头帧,常见触发原因:

  • 摄像头索引错误:cv2.VideoCapture(1)指定的设备索引不存在,多数默认摄像头的索引为0
  • 摄像头被其他程序占用:比如浏览器、视频会议软件正在使用摄像头
  • 程序无摄像头访问权限:系统隐私设置禁止当前Python环境访问相机
  • 摄像头硬件异常:设备未正确连接或故障

修复步骤

  1. 修正摄像头索引
    将cap = cv2.VideoCapture(1)改为cap = cv2.VideoCapture(0);如果仍无效,可运行以下代码测试所有可用摄像头索引:

    for i in range(5):
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            print(f"可用摄像头索引: {i}")
            cap.release()
    
  2. 增加帧读取校验
    在读取帧后立即判断ret值(ret为True表示帧读取成功),避免后续函数处理空帧:

    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头帧,退出程序")
        break
    
  3. 检查摄像头权限

    • Windows:打开「设置-隐私和安全性-相机」,确保当前Python环境(如Anaconda、VS Code)被允许访问相机
    • macOS:打开「系统设置-隐私与安全性-相机」,勾选对应程序
    • Linux:运行命令sudo usermod -aG video $USER,重启系统后赋予用户摄像头访问权限
  4. 确认摄像头状态
    关闭所有可能占用摄像头的程序(如微信、Zoom、浏览器摄像头页面),检查摄像头硬件连接是否正常

修复后的完整代码

# Importamos librerias
import torch
import cv2
import numpy as np
import pandas

# Leemos el modelo
model = torch.hub.load('ultralytics/yolov5', 'custom',
                       path = 'C:/Users/maxim/OneDrive/Documentos/jupyterbooks/detector.pt')

# Realizo Videocaptura - 使用默认摄像头索引0
cap = cv2.VideoCapture(0)

# 检查摄像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头,请检查设备连接或权限")
    exit()

# Empezamos
while True:
    # Realizamos lectura de frames
    ret, frame = cap.read()

    # 校验帧是否读取成功
    if not ret:
        print("无法读取摄像头帧,退出程序")
        break

    # Correccion de color
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # Realizamos las detecciones
    detect = model(frame)
    
    # Mostramos FPS
    cv2.imshow('Detector de Figuras', np.squeeze(detect.render()))

    # Leemos el teclado
    t = cv2.waitKey(5)
    if t == 27:
        break

cap.release()
cv2.destroyAllWindows()

内容的提问来源于stack exchange,提问作者Maximiliano Cerda Cid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:35:24