Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Webcam capture for python - Pops up a preview from your webcam and snaps a picture when you press 'q'
import cv2
# Windows dependencies
# - Python 2.7.6: http://www.python.org/download/
# - OpenCV: http://opencv.org/
# - Numpy -- get numpy from here because the official builds don't support x64:
# http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
# Mac Dependencies
# - brew install python
# - pip install numpy
# - brew tap homebrew/science
# - brew install opencv
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
cv2.imshow('frame', rgb)
if cv2.waitKey(1) & 0xFF == ord('q'):
out = cv2.imwrite('capture.jpg', frame)
break
cap.release()
cv2.destroyAllWindows()
@bathicodes
Copy link

bathicodes commented Jul 28, 2019

I'm having below issue and program terminated. Do you know any solutions for that?

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

@cbednarski
Copy link
Author

cbednarski commented Jul 28, 2019

@BathiyaSeneviratne I saw on Stack Overflow that you're using MacOS. I don't recognize this error code but I suspect it may have to do with recent-ish changes to MacOS webcam security policy. You'll probably need to whitelist python or opencv to access the webcam. System Preferences -> Security & Privacy -> Camera.

@bathicodes
Copy link

bathicodes commented Aug 1, 2019

@cbednarski thanks for the reply. Yes it's happening because of apple's security policy. is there any other ways to overcome this issue. because when I'm using Pycharm with OpenCV there are no apps that requesting the permission to access the camera in System Preferences -> Security & Privacy -> Camera.
Screen Shot 2019-08-01 at 8 22 02 AM

@berkaykurkcu
Copy link

berkaykurkcu commented Jan 29, 2020

I just had the same problem and instead of running the script on an iDE I opened up Terminal on Mac and cd 'd into the folder that contained .py file and ran it and it worked
python 3 face-det-cam.py

If you run this for the first time it may ask for a permission. I have not tried it for a 3rd party terminal i.e. iTerm2 but process must be the same

@bathicodes
Copy link

bathicodes commented Feb 1, 2020

Yes! I did the same thing. But it is much easier to run it with the visual studio code. Because it has access to the Mac native terminal

@Char-an-R
Copy link

Char-an-R commented Apr 9, 2021

I just had the same problem and instead of running the script on an iDE I opened up Terminal on Mac and cd 'd into the folder that contained .py file and ran it and it worked
python 3 face-det-cam.py

If you run this for the first time it may ask for a permission. I have not tried it for a 3rd party terminal i.e. iTerm2 but process must be the same

Thanks man it helped a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment