Skip to content

Instantly share code, notes, and snippets.

@mjmare
Created January 19, 2014 11:00
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 mjmare/8503306 to your computer and use it in GitHub Desktop.
Save mjmare/8503306 to your computer and use it in GitHub Desktop.
Slightly modified example to simulate motion detection and incrementing video file names
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