picamera motion detection - super hacky!
This file contains 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
from picamera import PiCamera, PiCameraCircularIO, PiVideoFrameType | |
from picamera.array import PiRGBArray | |
from time import sleep | |
import io | |
import cv2 | |
def diff_image(t0, t1, t2): | |
d1 = cv2.absdiff(t2, t1) | |
d2 = cv2.absdiff(t1, t0) | |
return cv2.bitwise_and(d1, d2) | |
def detect_motion(): | |
for frame in stream.frames: | |
print(frame) | |
#print(stream.frames[0]) | |
def write_video(stream): | |
print("writing") | |
with stream.lock: | |
# Find the first header frame in the video | |
for frame in stream.frames: | |
if frame.frame_type == PiVideoFrameType.sps_header: | |
stream.seek(frame.position) | |
break | |
# Write the rest of the stream to disk | |
with io.open('video.h264', 'wb') as output: | |
output.write(stream.read()) | |
with PiCamera(resolution="1056x768") as cam: | |
capture_stream = PiRGBArray(cam) | |
stream = PiCameraCircularIO(cam, seconds=30) | |
images = [] | |
try: | |
cam.start_preview(alpha = 192) | |
cam.framerate = 10 | |
cam.start_recording(stream, format="h264") | |
cam.color_effects = (128,128) | |
print("recording") | |
while True: | |
cam.capture(capture_stream, format='bgr') | |
images.append(cv2.cvtColor(capture_stream.array, cv2.COLOR_RGB2GRAY)) | |
capture_stream.truncate(0) | |
if len(images) == 3: | |
#print("diff") | |
diff = diff_image(images[0], images[1], images[2]) | |
#for i in range(len(images)): | |
# cv2.imwrite("image{}.png".format(i), images[i]) | |
#cv2.imwrite("diff.png", diff) | |
if cv2.countNonZero(diff) > 300000: | |
print("motion") | |
#print(cv2.countNonZero(diff)) | |
images.pop(0) | |
#cam.wait_recording(0.1) | |
#input("press enter") | |
#write_video(stream) | |
finally: | |
cam.stop_recording() | |
cam.stop_preview() | |
print("finished") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment