How to correctly check if a camera is available?
Another solution, which is available in Linux is to use the /dev/videoX
device in the VideoCapture()
call. The devices are there when the cam is plugged in. Together with glob()
, it is trivial to get all the cameras:
import cv2, glob
for camera in glob.glob("/dev/video?"):
c = cv2.VideoCapture(camera)
Of course a check is needed on c
using isOpened()
, but you are sure you only scan the available cameras.
Using cv2.VideoCapture( invalid device number )
does not throw exceptions. It constructs a <VideoCapture object>
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