cv2.VideoCapture(0)获取USB摄像头失败解决方案

问题:台式机没有摄像头,外接USB摄像头,通过 cv2.VideoCapture(0)捕获视频图像报错

[ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -2147024809
[ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -2147024809
[ WARN:1] videoio(MSMF): can't grab frame. Error: -2147024809
[ WARN:1] terminating async callback

如果是在笔记本上,默认摄像头是自带的那个摄像头,索引号为0,可是如果外接USB摄像头,它的索引号就不一定是0 ,或者像大多数博客中写道的1,2,3…… 

解决方案:修改源代码,循环暴力破解摄像头设备ID

import cv2
ID = 0
while(1):
    cap = cv2.VideoCapture(ID)
    # get a frame
    ret, frame = cap.read()
    if ret == False:
        ID += 1
    else:
        print(ID)
        break

 [ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -2147024809
[ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -2147024809
[ WARN:1] videoio(MSMF): can't grab frame. Error: -2147024809
[ WARN:1] terminating async callback
700

因此,我们得到自己的摄像头ID为700,然后将ID =  0 替换为700 ,就可以了!!! 

import cv2
ID = 700
cap = cv2.VideoCapture(ID)
while(1):
    # get a frame
    ret, frame = cap.read()
    # show a frame
    cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows() 

程序段里:

1、cap = cv2.VideoCapture(0)

VideoCapture()中参数是0,表示打开笔记本的内置摄像头,其他数字则代表其他设备;参数是视频文件路径则打开视频,如cap = cv2.VideoCapture(“../test.avi”)

2、ret,frame = cap.read()

cap.read()按帧读取视频,ret,frame是获cap.read()方法的两个返回值。其中ret是布尔值,如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False。frame就是每一帧的图像,是个三维矩阵。

你可能感兴趣的:(OpenCV,openCV,VideoCapture,python,摄像头)