Problems Using Webcam with cv2 (mac)

I’m on a mac and I am trying to open a window that shows the webcam feed on my Mac, but when I run the code I receive the error “Python quit unexpectedly” and no video feed pops up. Here is my code:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()

    cv2.imshow('frame', frame)

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

cap.release()
cv2.destroyAllWindows()

I am using IDLE on a Mac with Python 3. If anyone has any ideas about what is wrong with my code please tell me. Thanks!

Hi Jack,

I can only give you very limited help, as I don’t have a Mac, or your
webcam, nor do I use cv2.

Firstly, please try removing IDLE from the equation. Can you try running
your code without IDLE, directly in Python: save it to a .py file, then
in the Mac OS terminal or console, run:

python3 myfile.py

You may need to adjust the name of the file of course.

If that works, then you have identified a bug in IDLE. If it also
crashes, then we can go onto step 2: identifying the exact line where it
crashes.

Start a new file test.py and put this alone in it:

import cv2

and run it. Does it crash? If it crashes, you have identified the fault.
If it doesn’t crash, then go on to the second line:

import cv2
import numpy as np

If it crashes now, then you have identified the fault: numpy. If not,
move on to the next, adding one line at a time.

import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

(I say “add one line at a time”, but sometimes you may need to add
two lines to actually get legal Python code.)

Eventually you will add one line and it will crash again. Now you have
identified where the problem is, and we can hopefully move on to solving
it.

Thanks! I had to run it in Terminal, and it worked perfectly!