请问python如何使用opencv调用摄像头 并且录下监控内容 另外在尝试调用摄像头时有如下问题

这是代码:
import cv2
import numpy

    cap = cv2.VideoCapture(0)# 调整参数实现读取视频或调用摄像头
while 1:
ret, frame = cap.read()
cv2.imshow("cap", frame)
if cv2.waitKey(100) & 0xff == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

这是错误图片:

[ WARN:0@0.385] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (539) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Traceback (most recent call last):
File "D:\Learn\PyCharm\Test\OP.py", line 44, in <module>
cv2.imshow("cap", frame)
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

请大佬们帮帮忙

回答

如果不是内置的摄像头就把0改成其它数字
附:暴力找设备号

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
THE END
分享
二维码
< <上一篇
下一篇>>