motion.py 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import cv2
  2. import imutils
  3. import numpy as np
  4. class MotionDetector():
  5. def __init__(self, frame_shape, mask, resize_factor=4):
  6. self.resize_factor = resize_factor
  7. self.motion_frame_size = (int(frame_shape[0]/resize_factor), int(frame_shape[1]/resize_factor))
  8. self.avg_frame = np.zeros(self.motion_frame_size, np.float)
  9. self.avg_delta = np.zeros(self.motion_frame_size, np.float)
  10. self.motion_frame_count = 0
  11. self.frame_counter = 0
  12. resized_mask = cv2.resize(mask, dsize=(self.motion_frame_size[1], self.motion_frame_size[0]), interpolation=cv2.INTER_LINEAR)
  13. self.mask = np.where(resized_mask==[0])
  14. def detect(self, frame):
  15. motion_boxes = []
  16. # resize frame
  17. resized_frame = cv2.resize(frame, dsize=(self.motion_frame_size[1], self.motion_frame_size[0]), interpolation=cv2.INTER_LINEAR)
  18. # convert to grayscale
  19. gray = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2GRAY)
  20. # mask frame
  21. gray[self.mask] = [255]
  22. # it takes ~30 frames to establish a baseline
  23. # dont bother looking for motion
  24. if self.frame_counter < 30:
  25. self.frame_counter += 1
  26. else:
  27. # compare to average
  28. frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(self.avg_frame))
  29. # compute the average delta over the past few frames
  30. # the alpha value can be modified to configure how sensitive the motion detection is.
  31. # higher values mean the current frame impacts the delta a lot, and a single raindrop may
  32. # register as motion, too low and a fast moving person wont be detected as motion
  33. # this also assumes that a person is in the same location across more than a single frame
  34. cv2.accumulateWeighted(frameDelta, self.avg_delta, 0.2)
  35. # compute the threshold image for the current frame
  36. current_thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
  37. # black out everything in the avg_delta where there isnt motion in the current frame
  38. avg_delta_image = cv2.convertScaleAbs(self.avg_delta)
  39. avg_delta_image[np.where(current_thresh==[0])] = [0]
  40. # then look for deltas above the threshold, but only in areas where there is a delta
  41. # in the current frame. this prevents deltas from previous frames from being included
  42. thresh = cv2.threshold(avg_delta_image, 25, 255, cv2.THRESH_BINARY)[1]
  43. # dilate the thresholded image to fill in holes, then find contours
  44. # on thresholded image
  45. thresh = cv2.dilate(thresh, None, iterations=2)
  46. cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  47. cnts = imutils.grab_contours(cnts)
  48. # loop over the contours
  49. for c in cnts:
  50. # if the contour is big enough, count it as motion
  51. contour_area = cv2.contourArea(c)
  52. if contour_area > 100:
  53. x, y, w, h = cv2.boundingRect(c)
  54. motion_boxes.append((x*self.resize_factor, y*self.resize_factor, (x+w)*self.resize_factor, (y+h)*self.resize_factor))
  55. if len(motion_boxes) > 0:
  56. self.motion_frame_count += 1
  57. # TODO: this really depends on FPS
  58. if self.motion_frame_count >= 10:
  59. # only average in the current frame if the difference persists for at least 3 frames
  60. cv2.accumulateWeighted(gray, self.avg_frame, 0.2)
  61. else:
  62. # when no motion, just keep averaging the frames together
  63. cv2.accumulateWeighted(gray, self.avg_frame, 0.2)
  64. self.motion_frame_count = 0
  65. return motion_boxes