albertyw/albertyw.com

View on GitHub
app/notes/20170507-1743.md

Summary

Maintainability
Test Coverage
How to Capture a Camera Image With Python

capture-image-python

1494179029

While working on [sky-color](https://github.com/albertyw/sky-color), I found
that taking a photo using a webcam with python was pretty hard.  [opencv](https://github.com/opencv/opencv)
has some pretty opaque documentation since it's primarily written for C
developers and [simplecv](https://github.com/sightmachine/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:

```text
numpy==1.12.1
opencv-python==3.2.0.7
```

Code:

```python
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](http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html)