Issue: Unable to Stream Webcam Properly in OpenCV

Hi everyone,

I’m trying to test if I can stream my camera feed in OpenCV. I have two cameras connected to my laptop:

  1. The built-in webcam.
  2. An external Logitech C270 webcam.

Both cameras work fine when I use them in VLC or the Windows Camera app. However, I’m facing issues with OpenCV:

  • When I use cv2.VideoCapture(0), I get the error:
    Error: Could not open webcam.
  • When I use cv2.VideoCapture(1), I don’t see any error, but the displayed frame is completely black. I suspect index 1 should be the correct index for my external camera.

Additionally:

  • When I run the code with index 1, the external camera becomes inaccessible in other programs, which makes sense since OpenCV takes control of the device.
  • I’ve ensured that Python 3.11 has permission to access the camera under Windows settings, and the camera usage indicator confirms that the camera is being used.
  • The issue doesn’t seem to be related to VS Code. I get the same behavior when running the script directly from the terminal.

I can’t figure out:

  1. Why I can’t access my built-in webcam (index 0).
  2. Why my external camera (index 1) shows a black screen in OpenCV.

Here’s my code:

import cv2

def main():
    print("Press 'q' to quit the program.")
    # Open a connection to the webcam (0 is the default camera)
    cap = cv2.VideoCapture(0)

    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return

    # Allow the camera to warm up
    cv2.waitKey(1000)

    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()

        if not ret:
            print("Error: Could not read frame.")
            break

        # Display the resulting frame
        cv2.imshow('Webcam Stream', frame)

        # Break the loop on 'q' key press
        if cv2.waitKey(1) == ord('q'):
            break

    # When everything is done, release the capture
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

I would appreciate any advice on how to debug or resolve this issue. Are there additional configurations I should be checking? Is there a better way to test both cameras?

Thanks in advance!

crosspost:

brand and model of the internal camera? specs?

ffprobe for video modes?

https://trac.ffmpeg.org/wiki/Capture/Webcam