python用opencv打开外接摄像头_使用OpenCV-Python外接摄像头打不开问题

使用OpenCV-Python外接摄像头打不开

情况描述

使用OpenCV-Python打开摄像头常用的代码是这样的:

import cv2 as cv

cap = cv.VideoCapture(0)

flag = cap.isOpened()

while (flag):

ret, frame = cap.read()

笔者采用这种方法来打开电脑自带的摄像头是没有问题的,但是近期购入的一个新的摄像头,发现采用这种方式打开会提示:

WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1113) SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072875772

[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1125) SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072875772

[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072875772

[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback

经查阅资料

找到了问题所在,采用默认的API控制出错。

解决方法

在VideoCapture后加上cv.CAP_DSHOW

修正后代码如下:

import cv2 as cv

cap = cv.VideoCapture(1,cv.CAP_DSHOW) #更改API设置

flag = cap.isOpened()

index = 1

while (flag):

ret, frame = cap.read()

frame = cv.flip(frame, 1) # 水平翻转

cv.imshow("Capture_Paizhao", frame)

k = cv.waitKey(1) & 0xFF

if k == ord('s'): # 按下s键,进入下面的保存图片操作

cv.imwrite(r"F:\PyCharm\Camera calibration\Aruco_Identify\0" + str(index) + ".jpg", frame)

print(cap.get(3))

print(cap.get(4))

print("save" + str(index) + ".jpg successfuly!")

print("-------------------------")

index += 1

elif k == ord('q'): # 按下q键,程序退出

break

cap.release()

cv.destroyAllWindows()

你可能感兴趣的:(python用opencv打开外接摄像头_使用OpenCV-Python外接摄像头打不开问题)