Simple Python Photo Booth Script
I was just reminded of why I love Python so much. In a short 30-minute coding session, I was able to figure out how to take pictures using my laptop's webcam via the PyGame library, then take that image data and encode it into any arbitrary image type.
As a sample, check out what the script outputs for where I am currently sitting (at George Mason University):
fsufitch@callisto:~/$ python photobooth.py gmu.jpg
And of course, in open source nerd spirit, the source code of photobooth.py is:
from pygame import camera from PIL import Image from mimetypes import guess_type import sys def take_picture(): camera.init() cam_id = camera.list_cameras()[0] cam = camera.Camera(cam_id) cam.start() image = cam.get_image() cam.stop() data = [] for y in range(0, image.get_height()): row = [] for x in range(0, image.get_width()): r,g,b,a = image.get_at((x,y)) row.append( (r,g,b) ) data.append(row) return data def save_picture(filename, data): width = len(data[0]) height = len(data) im = Image.new('RGB', (width, height)) masheddata = [] for row in data: masheddata += row im.putdata(masheddata) im.save(filename) if __name__=='__main__': if len(sys.argv)<2: print "Need to specify filename." sys.exit(0) filename = sys.argv[1] if 'image' not in guess_type(filename)[0]: print "Invalid image filename." sys.exit(0) data = take_picture() save_picture(filename, data) print "Done."
Isn't that awesome?