└── MovingObjectDetection.py /MovingObjectDetection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def detect_moving_objects(): 4 | cap = cv2.VideoCapture(0) 5 | 6 | # Create a background subtractor object 7 | bg_subtractor = cv2.createBackgroundSubtractorMOG2() 8 | 9 | while True: 10 | ret, frame = cap.read() 11 | if not ret: 12 | break 13 | 14 | # Apply the background subtractor to get the foreground mask 15 | fg_mask = bg_subtractor.apply(frame) 16 | 17 | # Threshold the foreground mask to get binary image 18 | _, binary_image = cv2.threshold(fg_mask, 200, 255, cv2.THRESH_BINARY) 19 | 20 | # Find contours of moving objects 21 | contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 22 | 23 | # Draw rectangles around the moving objects 24 | for contour in contours: 25 | if cv2.contourArea(contour) > 500: # Adjust the minimum area as needed 26 | x, y, w, h = cv2.boundingRect(contour) 27 | cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) 28 | 29 | cv2.imshow("Moving Objects", frame) 30 | 31 | if cv2.waitKey(30) & 0xFF == 27: # Press 'Esc' to exit 32 | break 33 | 34 | cap.release() 35 | cv2.destroyAllWindows() 36 | 37 | if __name__ == "__main__": 38 | detect_moving_objects() --------------------------------------------------------------------------------