Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import os
- import struct
- import unittest
- import time
- import datetime
- import signal
- import subprocess
- def main():
- #If the pixel color difference between the image is
- #greather than the threshold then motion is detected
- THRESHOLD = 100000
- #Set the number of pixels to compare
- NO_PIXELS = 3000
- diff = 0
- first = True
- while True:
- os.system("fswebcam -d /dev/video0 -q -r 320x240 current.jpg")
- current_image = cv2.imread("current.jpg")
- if (first):
- prev_image = current_image
- first = False
- continue
- cnt = 0
- diff = 0
- width = current_image.shape[1]
- height = current_image.shape[0]
- for x in range(0,width):
- for y in range(0, height):
- cnt = cnt + 1
- if cnt == (width*height)/NO_PIXELS:
- pixel1 = current_image[y][x]
- pixel2 = prev_image[y][x]
- diff = diff + abs((int)(pixel1[2]) - (int)(pixel2[2]))
- diff = diff + abs((int)(pixel1[0]) - (int)(pixel2[0]))
- diff = diff + abs((int)(pixel1[1]) - (int)(pixel2[1]))
- cnt = 0
- if diff > THRESHOLD:
- print "Motion detected: "+str(diff)+".... resetting"
- # Play the famous 'trololo' video for 10 secs
- timeout_command("omxplayer /home/pi/video/trololo.mp4", 10)
- first = True
- continue
- print "Difference: "+str(diff)
- prev_image = current_image
- def timeout_command(command, timeout):
- cmd = command.split(" ")
- start = datetime.datetime.now()
- process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- while process.poll() is None:
- time.sleep(0.1)
- now = datetime.datetime.now()
- if (now - start).seconds > timeout:
- os.kill(process.pid, signal.SIGKILL)
- os.waitpid(-1, os.WNOHANG)
- return None
- return process.stdout.read()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement