Created
January 19, 2014 11:00
-
-
Save mjmare/8503306 to your computer and use it in GitHub Desktop.
Slightly modified example to simulate motion detection and incrementing video file names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import picamera | |
def detect_motion(camera): | |
stream = io.BytesIO() | |
camera.capture(stream, format='jpeg', use_video_port=True) | |
# Detect motion in the captured image. Presumably one would need a prior | |
# image here to compare to ... this is left as an exercise for the reader! | |
from random import randint | |
motion_detected = (randint(0,10) == 0) # fake motion detection | |
print "Motion detected" if motion_detected else "No motion" | |
return motion_detected | |
global_counter = 0 | |
def get_filename(): | |
global global_counter | |
global_counter += 1 | |
return 'motion%d.h264' % global_counter | |
def write_video(stream): | |
# Write the entire content of the circular buffer to disk | |
with io.open(get_filename(), 'wb') as output: | |
with stream.lock: | |
for frame in stream.frames: | |
if frame.header: | |
stream.seek(frame.position) | |
break | |
while True: | |
buf = stream.read1() | |
if not buf: | |
break | |
output.write(buf) | |
def main(camera): | |
stream = picamera.PiCameraCircularIO(camera, seconds=20) | |
camera.start_recording(stream, format='h264') | |
try: | |
while True: | |
camera.wait_recording(1) | |
if detect_motion(camera): | |
# Once we've detected motion, keep recording for 10 seconds | |
# and only then dump the stream to disk | |
camera.wait_recording(10) | |
write_video(stream) | |
finally: | |
camera.stop_recording() | |
if __name__ == '__main__': | |
with picamera.PiCamera() as camera: | |
camera.resolution = (1280, 720) | |
camera.vflip = True | |
camera.hflip = True | |
main(camera) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment