How to capture a camera image with python
While working on sky-color, I found that taking a photo using a webcam with python was pretty hard. opencv has some pretty opaque documentation since it’s primarily written for C developers and simplecv is dead and doesn’t support python 3. Stackoverflow is also filled with outdated incorrect answer. I therefore had to figure out a way to take a photo and save it to a file myself using python 3.6 and MacOS.
Prerequisites: Install numpy and opencv. My
requirements.txt file looks like:
import time import cv2 camera_id = 0 file_name = 'image.png' cam = cv2.VideoCapture(camera_id) time.sleep(1) # Give some time for the webcam to automatically adjust brightness levels ret_val, img = cam.read() cv2.imwrite(file_name, img)
Further reference: OpenCV API