You should first list the available camera ids
Here you can use G M's answer:
def list_ports():
is_working = True
dev_port = 0
working_ports = []
available_ports = []
while is_working:
camera = cv2.VideoCapture(dev_port)
if not camera.isOpened():
is_working = False
print("Port %s is not working." % dev_port)
else:
is_reading, img = camera.read()
w = camera.get(3)
h = camera.get(4)
if is_reading:
print("Port %s is working and reads images (%s x %s)" % (dev_port, h, w))
working_ports.append(dev_port)
else:
print("Port %s for camera ( %s x %s) is present but does not reads." % (dev_port, h, w))
available_ports.append(dev_port)
dev_port += 1
return available_ports, working_ports
Result will be:
Port 0 is working and reads images (720.0 x 1280.0)
OpenCV: out device of bound (0-0): 1
OpenCV: camera failed to properly initialize!
Port 1 is not working.
For instance, for my mac, camera id (cid
) 0 is available but not 1.
Therefore I initialized the code with cid
0.
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
while cap.isOpened():
success, img = cap.read()
if success:
cv2.imshow("Video", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
You should not initialize VideoCapture
object by default 0. Since it may not work. If there is no available port listed as a result, you may need an external camera.