Advertisement
steve-shambles-2109

Webcam Motion detect and save v1.7

Dec 4th, 2019
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.43 KB | None | 0 0
  1. """
  2. Webcam Motion detect and save v1.7
  3. By Steve Shambles
  4. stevepython.wordpress.com
  5. """
  6. import os
  7. import time
  8.  
  9. import cv2
  10. import numpy as np
  11.  
  12. motion_detect = 0
  13. md_switch = 'OFF'
  14.  
  15. # Check for folder.
  16. MYDIR = ('detected-images')
  17. CHECK_FOLDER = os.path.isdir(MYDIR)
  18. # If folder doesn't exist, then create it.
  19. if not CHECK_FOLDER:
  20.     os.makedirs(MYDIR)
  21.  
  22. os.chdir(MYDIR)
  23. CURR_TIME = time.asctime()
  24.  
  25. # Change sdthresh to suit camera and conditions,
  26. # 15-25 is usually within the threshold range.
  27. sdThresh = 20
  28.  
  29. # Used to count individualy named frames as jpgs.
  30. img_index = 0
  31.  
  32. # use this cv2 font
  33. font = cv2.FONT_HERSHEY_SIMPLEX
  34.  
  35. def distMap(frame1, frame2):
  36.     """outputs pythagorean distance between two frames"""
  37.     frame1_32 = np.float32(frame1)
  38.     frame2_32 = np.float32(frame2)
  39.     diff32 = frame1_32 - frame2_32
  40.     norm32 = np.sqrt(diff32[:,:,0]**2 + diff32[:,:,1]**2 +
  41.                      diff32[:,:,2]**2)/np.sqrt(255**2 + 255**2 + 255**2)
  42.     dist = np.uint8(norm32*255)
  43.     return dist
  44.  
  45. def print_date_time():
  46.     """Updates current date and time on to video"""
  47.     CURR_TIME = time.asctime()
  48.     cv2.putText(frame2,str(CURR_TIME),(280,24),
  49.                 font, 0.8, (0,255,0),2, cv2.LINE_AA)
  50.     cv2.putText(frame2,'Enter to pause. q to quit. Sensitivity = '+str
  51.                 (sdThresh)+'. Press + and - to change.' ,
  52.                 (10,450), font, 0.5,(255,255,255),1)
  53.     cv2.putText(frame2,'Save detected images is: '+str(md_switch)
  54.                 +'. press m to start auto saving. s to stop again.',
  55.                 (10,470), font, 0.5,(255,255,255),1)
  56.  
  57. # Capture video stream.
  58. cap = cv2.VideoCapture(0)
  59. _, frame1 = cap.read()
  60. _, frame2 = cap.read()
  61.  
  62. # Main loop.
  63. while(True):
  64.  
  65.     try:
  66.         _, frame3 = cap.read()
  67.         rows, cols, _ = np.shape(frame3)
  68.         dist = distMap(frame1, frame3)
  69.     except:
  70.         print('Camera not found.')
  71.         exit(0)
  72.  
  73.     frame1 = frame2
  74.     frame2 = frame3
  75.     keyPress = cv2.waitKey(20)
  76.  
  77.     # Apply Gaussian smoothing.
  78.     mod = cv2.GaussianBlur(dist, (9,9), 0)
  79.     # Apply thresholding.
  80.     _, thresh = cv2.threshold(mod, 100, 255, 0)
  81.     # Calculate st dev test.
  82.     _, stDev = cv2.meanStdDev(mod)
  83.  
  84.     # If motion is dectected.
  85.     if stDev > sdThresh :
  86.             cv2.putText(frame2,'MD '+str(img_index),
  87.                         (0,20),font, 0.8, (0,255,0),2, cv2.LINE_AA)
  88.             print_date_time()
  89.  
  90.             # Save jpg.
  91.             if motion_detect == 1:
  92.                 frame_name =(str(img_index)+str('.jpg'))
  93.                 cv2.imwrite(frame_name, frame2)
  94.                 img_index +=1
  95.  
  96.     print_date_time()
  97.     cv2.imshow('Live video', frame2)
  98.  
  99.     # Enter key pauses video stream.
  100.     if keyPress & 0xFF == 13:
  101.         cv2.putText(frame2,'PAUSED', (210,260),font, 2,
  102.                     (0,255,0),8, cv2.LINE_AA)
  103.         cv2.imshow('Live video', frame2)
  104.         cv2.waitKey(0)
  105.  
  106.     # Hold down Escape key to quit.
  107.     if keyPress & 0xFF == ord('q'):
  108.         break
  109.  
  110.     # Motion detection off.
  111.     if keyPress & 0xFF == ord('s'):
  112.         motion_detect = 0
  113.         md_switch = 'OFF'
  114.  
  115.     # Motion detection on.
  116.     if keyPress & 0xFF == ord('m'):
  117.         motion_detect = 1
  118.         md_switch = 'ON'
  119.  
  120.     # Sensitivity inc.
  121.     if keyPress & 0xFF == ord('+'):
  122.         sdThresh +=1
  123.  
  124.     # Sensitivity dec.
  125.     if keyPress & 0xFF == ord('-'):
  126.         sdThresh -= 1
  127.  
  128. cap.release()
  129. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement