'cv2 SystemError when using webcam on MacOS

I am trying to run a very simple script using opencv, which should display frames from my webcam (on a 2019 macbook pro running OS Catalina) until interrupted.

import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    key = cv2.waitKey(10)    
    if key == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

This results in the error SystemError: <class 'cv2.VideoCapture'> returned a result with an error set if I run it either through visual studio code or from the terminal in a virtual environment with python 3.8.12 and opencv 4.5.3

From what I gather, others have had problems with camera permissions, but I have not seen this error code reported in that context. If it is camera permissions I'm at a loss for how to allow access either through the terminal or through vs code. If it's not permissions I'm still at a loss for what to try next. Any suggestions would be greatly appreciated.

UPDATE: The root of the problem does indeed seem to be camera permission and more specifically coercing vs code to request camera access. The best workaround I have found is to run the script through the terminal or using a jupyter notebook not inside of cv code.



Solution 1:[1]

There are two suggestions I would like to mention.

#1: Enable your terminal or PyCharm to reach the camera.

Go to System Preferences-> Security and Privacy -> Camera and add PyCharm to the list.

enter image description here

#2 Instead of while True use while cap.isOpened(), so you can know that PyCharm or terminal can access your camera.

import cv2

frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)

while cap.isOpened():
    success, img = cap.read()
    if success:
        cv2.imshow("Result", img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Parthiban Marimuthu