#!/usr/bin/env python3 import sys import cv2 import numpy as np def detect_motion(image_path): # Read the input image frame = cv2.imread(image_path) if frame is None: print("Error: Could not read image file") sys.exit(1) # Convert to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Apply Gaussian blur to reduce noise blur = cv2.GaussianBlur(gray, (21, 21), 0) # Threshold the image to detect significant changes _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) # Find contours in the thresholded image contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Filter contours based on area to remove noise min_area = 500 motion_detected = False for contour in contours: if cv2.contourArea(contour) > min_area: motion_detected = True # Draw rectangle around motion area (x, y, w, h) = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Save the output image with motion detection boxes output_path = image_path.replace('.jpg', '_motion.jpg') cv2.imwrite(output_path, frame) # Return result if motion_detected: print("Motion detected!") print(f"Output saved to: {output_path}") else: print("No motion detected") if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python motion_detection.py ") sys.exit(1) detect_motion(sys.argv[1])