Forums

how to get camera frames using cv2.VideoCapture( )

The following script is intended to open and display the captured frames of 3 cameras (built-in webcam and 2 USB cameras), the script it's loaded as a file in this website, but when is executed from the online editor it can't open/detect the connected cameras.

import cv2

num_cameras = 3
cam_lst = []

for n in range(num_cameras):
    cam = cv2.VideoCapture(n)
    if cam.isOpened():
        cam_lst.append(cam)

while True:

    for index, c in enumerate(cam_lst):
        ret, frame = c.read()
        cv2.imshow('camera %i.jpg' %(index + 1), frame)

    k = cv2.waitKey(1) & 0xFF
    if k == ord('q'):
        break

for cam in cam_lst:
    cam.release()
cv2.destroyAllWindows()

output

The error is VIDEOIO ERROR: V4L: can't open camera by index 0
The error is VIDEOIO ERROR: V4L: can't open camera by index 1
The error is VIDEOIO ERROR: V4L: can't open camera by index 2

In linux is possible to specify the correct path for the "index" of cv2.VideoCapture(index) as /dev/video0, /dev/video1 and /dev/video2. In Windows the "index" can only be set as an integer as far as I know. I'm using Windows, how can I get access to the cameras from this online editor?

Also had a problem with cv2.waitKey(), tried to install gtk2.0 but failed miserably and just commented that part. This is the error if cv2.waitKey() is not commented:

File "/home/CesarCorona/cap/mult_cam.py", line 18, in <module>
    k = cv2.waitKey(1) & 0xFF
cv2.error: OpenCV(3.4.2) /io/opencv/modules/highgui/src/window.cpp:698: error: (-2:Unspecified error) The 
function is not implemented. Rebuild the library with Windo
ws, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run 
cmake or configure script in function 'cvWaitKey'

There are no cameras on PythonAnywhere, so there's nothing for the camera code to connect to.

You mean I can't use PythonAnywhere to interact with any kind of hardware?

Certainly not any hardware that is on a machine that is not on PythonAnywhere.

I see, thank you.