Advertisement
anta40

mdetect.v1

Sep 14th, 2015
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. import cv2
  2. import os
  3. import struct
  4. import unittest
  5. import time
  6. import datetime
  7. import signal
  8. import subprocess
  9.  
  10. def main():
  11.     #If the pixel color difference between the image is
  12.     #greather than the threshold then motion is detected
  13.     THRESHOLD = 100000
  14.  
  15.     #Set the number of pixels to compare
  16.     NO_PIXELS = 3000
  17.  
  18.     diff = 0
  19.     first = True
  20.  
  21.     while True:
  22.         os.system("fswebcam -d /dev/video0 -q -r 320x240 current.jpg")
  23.         current_image = cv2.imread("current.jpg")
  24.  
  25.         if (first):
  26.             prev_image = current_image
  27.             first = False
  28.             continue
  29.  
  30.         cnt = 0
  31.         diff = 0
  32.         width = current_image.shape[1]
  33.         height = current_image.shape[0]
  34.  
  35.         for x in range(0,width):
  36.             for y in range(0, height):
  37.                 cnt = cnt + 1
  38.                 if cnt == (width*height)/NO_PIXELS:
  39.                     pixel1 = current_image[y][x]
  40.                     pixel2 = prev_image[y][x]
  41.                     diff = diff + abs((int)(pixel1[2]) - (int)(pixel2[2]))
  42.                     diff = diff + abs((int)(pixel1[0]) - (int)(pixel2[0]))
  43.                     diff = diff + abs((int)(pixel1[1]) - (int)(pixel2[1]))
  44.                     cnt = 0
  45.  
  46.         if diff > THRESHOLD:
  47.             print "Motion detected: "+str(diff)+".... resetting"
  48.  
  49.             # Play the famous 'trololo' video for 10 secs
  50.             timeout_command("omxplayer /home/pi/video/trololo.mp4", 10)
  51.             first = True
  52.             continue
  53.         print "Difference: "+str(diff)
  54.         prev_image = current_image
  55.  
  56. def timeout_command(command, timeout):
  57.     cmd = command.split(" ")
  58.     start = datetime.datetime.now()
  59.     process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  60.  
  61.     while process.poll() is None:
  62.         time.sleep(0.1)
  63.         now = datetime.datetime.now()
  64.         if (now - start).seconds > timeout:
  65.             os.kill(process.pid, signal.SIGKILL)
  66.             os.waitpid(-1, os.WNOHANG)
  67.         return None
  68.  
  69.     return process.stdout.read()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement