Advertisement
steve-shambles-2109

Motion detect and save v1.93WL

Dec 11th, 2019
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.28 KB | None | 0 0
  1. """
  2. Motion detect and save v1.93WL
  3. By Steve Shambles
  4. stevepython.wordpress.com
  5. updated dec 2019
  6.  
  7. Tested on Win7 and Linux Mint 19.1.
  8.  
  9. pip install opencv-python
  10. pip install numpy
  11.  
  12. Based on intel detection algo, found here:
  13. https://software.intel.com/en-us/node/754940
  14.  
  15. """
  16. import os
  17. import subprocess
  18. import sys
  19. import time
  20. from tkinter import messagebox, Tk
  21. import webbrowser
  22.  
  23. import cv2
  24. import numpy as np
  25.  
  26. root = Tk()
  27. motion_detect = 0
  28. md_switch = 'OFF'
  29.  
  30. # check for folder.
  31. my_dir = ('detected-images')
  32. check_folder = os.path.isdir(my_dir)
  33.  
  34. # If folder doesn't exist, then create it.
  35. if not check_folder:
  36.     os.makedirs(my_dir)
  37.  
  38. # Make that folder current dir.
  39. os.chdir(my_dir)
  40.  
  41. # Change sdthresh (sensitivty) to suit camera and conditions,
  42. # 10-15 is usually within the threshold range.
  43. sdThresh = 15
  44.  
  45. # Used to count individualy named frames as jpgs.
  46. img_index = 0
  47.  
  48. # Use this cv2 font.
  49. font = cv2.FONT_HERSHEY_SIMPLEX
  50.  
  51. def open_folder():
  52.     """open systems file browser to view images folder."""
  53.     cwd = os.getcwd()
  54.     webbrowser.open(cwd)
  55.  
  56. def distMap(frame1, frame2):
  57.     """outputs pythagorean distance between two frames."""
  58.     frame1_32 = np.float32(frame1)
  59.     frame2_32 = np.float32(frame2)
  60.     diff32 = frame1_32 - frame2_32
  61.  
  62.     norm32 = np.sqrt(diff32[:, :, 0]**2 + diff32[:, :, 1]**2 + diff32[:, :, 2]
  63.                      **2)/np.sqrt(255**2 + 255**2 + 255**2)
  64.  
  65.     dist = np.uint8(norm32*255)
  66.     return dist
  67.  
  68. def print_date_time():
  69.     """Updates current date and time and keys info on to video."""
  70.     current_time = time.asctime()
  71.  
  72.     cv2.putText(frame2, str(current_time), (280, 24),
  73.                 font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)
  74.  
  75.     cv2.putText(frame2, '   Press h for options : Sensitivity = '
  76.                 +str(sdThresh)+' : Save detected images is: '+str(md_switch),
  77.                 (10, 470), font, 0.5, (255, 255, 255), 1)
  78.  
  79. # Capture video stream.
  80. cap = cv2.VideoCapture(0)
  81. _, frame1 = cap.read()
  82. _, frame2 = cap.read()
  83.  
  84. # Main loop.
  85. while True:
  86.  
  87.     # Report error if camera not found.
  88.     try:
  89.         _, frame3 = cap.read()
  90.         rows, cols, _ = np.shape(frame3)
  91.         dist = distMap(frame1, frame3)
  92.     except:
  93.         print('Camera not found.')
  94.         exit(0)
  95.  
  96.     frame1 = frame2
  97.     frame2 = frame3
  98.     keyPress = cv2.waitKey(20)
  99.  
  100.     # Apply Gaussian smoothing.
  101.     mod = cv2.GaussianBlur(dist, (9, 9), 0)
  102.     # Apply thresholding.
  103.     _, thresh = cv2.threshold(mod, 100, 255, 0)
  104.     # Calculate st dev test.
  105.     _, stDev = cv2.meanStdDev(mod)
  106.     # If motion is dectected.
  107.     if stDev > sdThresh:
  108.         # Motion is detected.
  109.         cv2.putText(frame2, 'MD '+str(img_index),
  110.                     (0, 20), font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)
  111.         print_date_time()
  112.  
  113.         # Save a timestamped jpg if motion detected.
  114.         if motion_detect == 1:
  115.             frame_name = (str(img_index)+str('.jpg'))
  116.             cv2.imwrite(frame_name, frame2)
  117.             img_index += 1
  118.  
  119.     print_date_time()
  120.     cv2.imshow('Live video', frame2)
  121.  
  122.     # Enter key pauses video stream.
  123.     if keyPress & 0xFF == 13:
  124.         cv2.putText(frame2, 'PAUSED', (210, 260), font, 2,
  125.                     (0, 255, 0), 8, cv2.LINE_AA)
  126.         cv2.imshow('Live video', frame2)
  127.         cv2.waitKey(0)
  128.  
  129.     # q key to quit program.
  130.     if keyPress & 0xFF == ord('q'):
  131.         root.withdraw()
  132.         ask_yn = messagebox.askyesno('Quit Motion Detector?',
  133.                                      'Are you sure?')
  134.         if ask_yn:
  135.             break
  136.         root.update_idletasks()
  137.  
  138.     # Motion detect off. s key.
  139.     if keyPress & 0xFF == ord('s'):
  140.         motion_detect = 0
  141.         md_switch = 'OFF'
  142.  
  143.     # Motion detect on. m key.
  144.     if keyPress & 0xFF == ord('m'):
  145.         motion_detect = 1
  146.         md_switch = 'ON'
  147.  
  148.     # Camera sensitivity + key.
  149.     if keyPress & 0xFF == ord('+'):
  150.         sdThresh += 1
  151.  
  152.     # Camera sensitivity - key.
  153.     if keyPress & 0xFF == ord('-'):
  154.         sdThresh -= 1
  155.  
  156.     # View images folder v key.
  157.     if keyPress & 0xFF == ord('v'):
  158.         open_folder()
  159.  
  160.     # Snapshot x key.
  161.     if keyPress & 0xFF == ord('x'):
  162.         frame_name = (str(img_index)+str('-snapshot.jpg'))
  163.         cv2.imwrite(frame_name, frame2)
  164.         img_index += 1
  165.  
  166.     # Help keys msg box.
  167.     if keyPress & 0xFF == ord('h'):
  168.         root.withdraw()
  169.         messagebox.showinfo('Motion Detector help - Keys',
  170.                             'H ~ This menu\n\n'
  171.                             'M ~ Start motion dectect\n\n'
  172.                             'S ~ Stop motion detect\n\n'
  173.                             'X ~ Take a single snaphot\n\n'
  174.                             'V ~ View images folder\n\n'
  175.                             '+ ~ Camera sensitivity increase\n\n'
  176.                             '- ~ Camera sensitivity deccrease\n\n'
  177.                             'Q ~ Quit\n\n'
  178.                             'ENTER - Pause video stream\n\n'
  179.                             'Motion Detector V1.93WL is Freeware.\n'
  180.                             'By Steve Shambles, Dec 2019.\n'
  181.                             'Visit my Python blog at:\n'
  182.                             'stevepython.wordpress.com'
  183.                             )
  184.  
  185. # Close down.
  186. cap.release()
  187. cv2.destroyAllWindows()
  188.  
  189. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement