skip to Main Content

I want to run the following Python code from this OpenCV tutorial in VS Code:

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

I also get the following error from VS Code’s terminal:

[ WARN:[email protected]] global /private/var/folders/sy/f16zz6x50xz3113nwtb9bvq00000gp/T/abs_506zufg7xt/croots/recipe/opencv-suite_1664548331847/work/modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created

I believe that my interpreter/virtualenv is correct. My camera’s little green light does seem to turn on, if only briefly. The camera works perfectly fine in other situations. But I don’t seem to get past the first line of code cap = cv.VideoCapture(0) when I run it. Any ideas on what is going on?

3

Answers


  1. Chosen as BEST ANSWER

    I forgot to return here to report on my solution. It turns out that VS Code does not play nicely with conda-based environments. I created a new environment with Python venv; everything now works like a charm.


  2. It says that your OpenCV needs Gstreamer as backend to access your camera, but you haven’t compiled a Gstreamer-enabled OpenCV.

    Login or Signup to reply.
  3. You appear to be on Mac OS. Use this:

    cap = cv.VideoCapture(0, apiPreference=cv.CAP_AVFOUNDATION)
    

    Explicit apiPreference skips auto-detection of a backend, so the gstreamer backend won’t even be attempted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search