I am using OpenCV to open and read from several webcams. It all works fine, but I cannot seem to find a way to know if a camera is available.
I tried this code (cam
Using cv2.VideoCapture( invalid device number )
does not throw exceptions. It constructs a
containing an invalid device - if you use it you get exceptions.
Test the constructed object for None
and not isOpened()
to weed out invalid ones.
For me this works (1 laptop camera device):
import cv2 as cv
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
testDevice(0) # no printout
testDevice(1) # prints message
Output with 1:
Warning: unable to open video source: 1
Example from: https://github.com/opencv/opencv_contrib/blob/master/samples/python2/video.py lines 159ff
cap = cv.VideoCapture(source) if 'size' in params: w, h = map(int, params['size'].split('x')) cap.set(cv.CAP_PROP_FRAME_WIDTH, w) cap.set(cv.CAP_PROP_FRAME_HEIGHT, h) if cap is None or not cap.isOpened(): print 'Warning: unable to open video source: ', source