【无标题】python之cv2.VideoCapture()用电脑自带摄像头捕获画面失败ret一直返回False解决方案。

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    ret,frame = cap.read()

    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)

    press_key = cv2.waitKey(1)

    if press_key == 27:

        break

cap.release()

cv2.destroyAllWindows()

程序运行时,视频头能正常打开,但是报错:

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

_src empty提示获取捕获的摄像头数据为空,书本中或者是网络上一直都说电脑自带摄像头默认ID为0,但是在ID为0的前提下,我在网上找了三四天有提示摄像头权限未开启、系统环境不正确,但更改这些操作后仍不能解决上述报错。

后来才想到有没可能摄像头默认ID是0,但是其实电脑设备厂商另有设定,于是用下述方法,循环检测电脑摄像头ID值,当ret获取值为True时,返回对应ID:

import cv2

ID = 0

while(1):

    cap = cv2.VideoCapture(ID)

    ret,frame = cap.read()

    if ret == False:

        ID += 1

    elif ID >= 10000:

        break

    else:

        print(ID)

        break

cap.release()

最终获取自带摄像头ID为700,现将初始化摄像头cv2.VideoCapture(700)中的0改为700,成功获取画面:

import cv2
import numpy as np

cap = cv2.VideoCapture(700)

while (1):

    ret ,frame = cap.read()

    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)

    press_key = cv2.waitKey(1)

    if press_key == 27:

        break

cap.release()

cv2.destroyAllWindows()

 【无标题】python之cv2.VideoCapture()用电脑自带摄像头捕获画面失败ret一直返回False解决方案。_第1张图片

 

你可能感兴趣的:(python,opencv,计算机视觉)