101prairiedogs

Movement Detection in Python using CV2 - Video Recording Aid

Nov 8th, 2018
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. # This program uses the camera feed from the first available webcam and only records when motion is detected
  2. # It could be used to detect motion on a pre-recorded video, just replace cv2.VideoCapture(0) with cv2.VideoCapture('<Path to video>')
  3. # This program outputs a .avi file that contains any recorded motion
  4.  
  5. import cv2
  6. import numpy as np
  7.  
  8. cap = cv2.VideoCapture(0)
  9. fgbg = cv2.createBackgroundSubtractorMOG2()
  10.  
  11. if cap.isOpened() == False:
  12.     print('Unable to read camera feed')
  13.  
  14. width = int(cap.get(3))
  15. height = int(cap.get(4))
  16. print(width, height)
  17.  
  18. fps = 30.0
  19. fourcc = cv2.VideoWriter_fourcc(*'XVID')
  20. out = cv2.VideoWriter('out.avi', fourcc, fps, (width, height))
  21.  
  22. kernel = np.ones((15, 15), np.float32)/225
  23.  
  24. while True:
  25.     ret, frame = cap.read()
  26.     if ret:
  27.         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  28.         mask = fgbg.apply(gray)
  29.         retval, threshold = cv2.threshold(mask, 150, 255, cv2.THRESH_BINARY)
  30.         smooth = cv2.filter2D(threshold, -1, kernel)
  31.        
  32.         cv2.imshow('Smoothed', smooth)
  33.         cv2.imshow('Masked', mask)
  34.         cv2.imshow('Frame', frame)
  35.        
  36.         if cv2.countNonZero(mask) >= 1000:
  37.             print('Recording')
  38.             out.write(frame)
  39.         else:
  40.             print('Not Recording')
  41.  
  42.         if cv2.waitKey(1) & 0xFF == ord('q'):
  43.             break
  44.     else:
  45.         break
  46.  
  47. cap.release()
  48. out.release()
  49. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment