Listing available devices in python-opencv

I have been able to work around this problem by iterating over the webcam indexes until reading that camera no longer returns anything:

index = 0
arr = []
while True:
    cap = cv2.VideoCapture(index)
    if not cap.read()[0]:
        break
    else:
        arr.append(index)
    cap.release()
    index += 1
return arr

This method returns a list of all indexes that return something when read; I’m sure it can be improved upon, but there are hardly ever more than a few webcams and this runs pretty quickly.

Leave a Comment