motion.py 3.9 KB

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