Skip to content

Instantly share code, notes, and snippets.

@KoffeinFlummi
Created July 22, 2014 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KoffeinFlummi/57e8053ee33c1954648a to your computer and use it in GitHub Desktop.
Save KoffeinFlummi/57e8053ee33c1954648a to your computer and use it in GitHub Desktop.
Bewegungsmelder - Raspberry Pi
#!/usr/bin/python
import StringIO
import subprocess
import time
import datetime
import math
from PIL import Image
from PIL import ImageChops
frames = []
def get_difference(image1, image2):
""" Returns the numerical difference between two PIL Image objects. """
histogram = ImageChops.difference(image1, image2).histogram()
histogram_sum = sum(histogram)
samples_probability = [float(h) / histogram_sum for h in histogram]
return -sum([p * math.log(p, 2) for p in samples_probability if p != 0])
def check_for_movement():
""" Checks the last 2 frames for movement. """
global frames
if len(frames) < 2:
return 0
image1 = frames.pop(0)
image2 = frames[0]
return get_difference(image1, image2)
def take_test_picture():
""" Takes a small test image used for detecting changes. """
global frames
command = "raspistill -w 160 -h 90 -t 200 -e bmp -n -o -"
stream = StringIO.StringIO()
stream.write(subprocess.check_output(command, shell=True))
stream.seek(0)
frames.append(Image.open(stream))
def take_full_picture():
""" Takes a proper picture and stores it. """
time = datetime.datetime.now()
filename = "capture/%04d%02d%02d-%02d%02d%02d.jpg" % (time.year, time.month, time.day, time.hour, time.minute, time.second)
subprocess.call("raspistill -w 1280 -h 720 -t 200 -e jpg -q 20 -n -o %s" % (filename), shell=True)
def main():
while True:
take_test_picture()
movement = check_for_movement()
if movement > 5:
print "Bewegung erkannt."
take_full_picture()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment