Camera

Want to take photos with your built in web-cam for a Python project? Then this is for you! To use this library to take a photo, the final code in your project will be as simple as this:

import camera

cam = camera.Camera()
cam.save_photo("photo.jpg")

Python requirements

camera.py

Save the following as camera.py in your project folder and you are good to go! It has been tested on Raspberry Pi 3, Microsoft Windows 10, and Mac OSX High Sierra.

import cv2
import numpy as np
from PIL import Image

class Camera():
    def __init__(self, camera_device_id=0, width=1920, height=1080):
        self.camera_device_id = camera_device_id
        self.camera_height = height
        self.camera_width = width
        self.flip = False

    def set_flip(self, flip):
        # Useful for Raspberry Pi
        self.flip = flip

    def get_photo(self):
        # Connect to camera
        cap = cv2.VideoCapture(self.camera_device_id)
        cap.set(3, self.camera_width)
        cap.set(4, self.camera_height)
        # Get image
        ret, img = cap.read()
        assert ret, "Error reading from capture device "+str(self.camera_device_id)
        if self.flip:
            img = cv2.flip(img, -1)
        cv2_image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        pil_image = Image.fromarray(cv2_image_rgb)
        return pil_image

    def save_photo(self, file_name="photo.jpg"):
        im = self.get_photo()
        im.save(file_name)