motion.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import cv2
  2. import imutils
  3. import numpy as np
  4. from frigate.config import MotionConfig
  5. class MotionDetector:
  6. def __init__(self, frame_shape, config: MotionConfig):
  7. self.config = config
  8. self.frame_shape = frame_shape
  9. self.resize_factor = frame_shape[0] / config.frame_height
  10. self.motion_frame_size = (
  11. config.frame_height,
  12. config.frame_height * frame_shape[1] // frame_shape[0],
  13. )
  14. self.avg_frame = np.zeros(self.motion_frame_size, np.float)
  15. self.avg_delta = np.zeros(self.motion_frame_size, np.float)
  16. self.motion_frame_count = 0
  17. self.frame_counter = 0
  18. resized_mask = cv2.resize(
  19. config.mask,
  20. dsize=(self.motion_frame_size[1], self.motion_frame_size[0]),
  21. interpolation=cv2.INTER_LINEAR,
  22. )
  23. self.mask = np.where(resized_mask == [0])
  24. def detect(self, frame):
  25. motion_boxes = []
  26. gray = frame[0 : self.frame_shape[0], 0 : self.frame_shape[1]]
  27. # resize frame
  28. resized_frame = cv2.resize(
  29. gray,
  30. dsize=(self.motion_frame_size[1], self.motion_frame_size[0]),
  31. interpolation=cv2.INTER_LINEAR,
  32. )
  33. # TODO: can I improve the contrast of the grayscale image here?
  34. # convert to grayscale
  35. # resized_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2GRAY)
  36. # mask frame
  37. resized_frame[self.mask] = [255]
  38. # it takes ~30 frames to establish a baseline
  39. # dont bother looking for motion
  40. if self.frame_counter < 30:
  41. self.frame_counter += 1
  42. else:
  43. # compare to average
  44. frameDelta = cv2.absdiff(resized_frame, cv2.convertScaleAbs(self.avg_frame))
  45. # compute the average delta over the past few frames
  46. # higher values mean the current frame impacts the delta a lot, and a single raindrop may
  47. # register as motion, too low and a fast moving person wont be detected as motion
  48. cv2.accumulateWeighted(frameDelta, self.avg_delta, self.config.delta_alpha)
  49. # compute the threshold image for the current frame
  50. # TODO: threshold
  51. current_thresh = cv2.threshold(
  52. frameDelta, self.config.threshold, 255, cv2.THRESH_BINARY
  53. )[1]
  54. # black out everything in the avg_delta where there isnt motion in the current frame
  55. avg_delta_image = cv2.convertScaleAbs(self.avg_delta)
  56. avg_delta_image = cv2.bitwise_and(avg_delta_image, current_thresh)
  57. # then look for deltas above the threshold, but only in areas where there is a delta
  58. # in the current frame. this prevents deltas from previous frames from being included
  59. thresh = cv2.threshold(
  60. avg_delta_image, self.config.threshold, 255, cv2.THRESH_BINARY
  61. )[1]
  62. # dilate the thresholded image to fill in holes, then find contours
  63. # on thresholded image
  64. thresh = cv2.dilate(thresh, None, iterations=2)
  65. cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  66. cnts = imutils.grab_contours(cnts)
  67. # loop over the contours
  68. for c in cnts:
  69. # if the contour is big enough, count it as motion
  70. contour_area = cv2.contourArea(c)
  71. if contour_area > self.config.contour_area:
  72. x, y, w, h = cv2.boundingRect(c)
  73. motion_boxes.append(
  74. (
  75. int(x * self.resize_factor),
  76. int(y * self.resize_factor),
  77. int((x + w) * self.resize_factor),
  78. int((y + h) * self.resize_factor),
  79. )
  80. )
  81. if len(motion_boxes) > 0:
  82. self.motion_frame_count += 1
  83. if self.motion_frame_count >= 10:
  84. # only average in the current frame if the difference persists for a bit
  85. cv2.accumulateWeighted(
  86. resized_frame, self.avg_frame, self.config.frame_alpha
  87. )
  88. else:
  89. # when no motion, just keep averaging the frames together
  90. cv2.accumulateWeighted(
  91. resized_frame, self.avg_frame, self.config.frame_alpha
  92. )
  93. self.motion_frame_count = 0
  94. return motion_boxes