Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
WebCam Motion Detector program in Python ?
A WebCam Motion Detector analyzes images from your webcam to detect movement and logs the time intervals when motion occurs. This program uses computer vision techniques to compare frames and identify changes.
Required Libraries
Install the required libraries using pip ?
pip install opencv-python pandas
How Motion Detection Works
Complete Motion Detector Code
# Import required libraries
import cv2
import pandas as pd
import time
from datetime import datetime
# Initialize variables
still_image = None
motion_list = [None, None]
time_list = []
# Initialize DataFrame with start and end time columns
df = pd.DataFrame(columns=["Start", "End"])
# Capture video from webcam (0 = default camera)
video = cv2.VideoCapture(0)
print("Motion detector started. Press 'q' to quit.")
while True:
# Read frame from video
check, frame = video.read()
motion = 0
# Convert to grayscale and apply Gaussian blur
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# Set first frame as reference background
if still_image is None:
still_image = gray
continue
# Calculate difference between background and current frame
diff_frame = cv2.absdiff(still_image, gray)
# Apply threshold to get binary image
thresh_frame = cv2.threshold(diff_frame, 25, 255, cv2.THRESH_BINARY)[1]
thresh_frame = cv2.dilate(thresh_frame, None, iterations=2)
# Find contours of moving objects
contours, hierarchy = cv2.findContours(thresh_frame.copy(),
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Check each contour for significant motion
for contour in contours:
if cv2.contourArea(contour) < 10000:
continue
motion = 1
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
# Track motion status
motion_list.append(motion)
motion_list = motion_list[-2:]
# Record start time of motion
if motion_list[-1] == 1 and motion_list[-2] == 0:
time_list.append(datetime.now())
# Record end time of motion
if motion_list[-1] == 0 and motion_list[-2] == 1:
time_list.append(datetime.now())
# Display frames
cv2.imshow("Grayscale Frame", gray)
cv2.imshow("Threshold Frame", thresh_frame)
cv2.imshow("Motion Detection", frame)
# Press 'q' to quit
key = cv2.waitKey(1)
if key == ord('q'):
if motion == 1:
time_list.append(datetime.now())
break
# Save motion time intervals to DataFrame
for i in range(0, len(time_list), 2):
if i + 1 < len(time_list):
new_row = pd.DataFrame({"Start": [time_list[i]], "End": [time_list[i + 1]]})
df = pd.concat([df, new_row], ignore_index=True)
# Save to CSV file
df.to_csv("motion_detection_log.csv", index=False)
print(f"Motion log saved with {len(df)} motion events")
# Cleanup
video.release()
cv2.destroyAllWindows()
Key Features
- Background Subtraction: Compares current frame with a reference background
- Noise Reduction: Uses Gaussian blur to reduce camera noise
- Contour Detection: Identifies moving objects and draws bounding boxes
- Time Logging: Records start and end times of motion events
- CSV Export: Saves motion data for analysis
Sample Output
The program displays three windows: grayscale view, threshold binary image, and colored frame with motion rectangles. The CSV file contains motion timestamps ?
Start,End 2024-02-21 18:08:35.791487,2024-02-21 18:10:59.718005 2024-02-21 18:15:22.456123,2024-02-21 18:16:45.789456
Customization Options
| Parameter | Default | Purpose |
|---|---|---|
| Threshold Value | 25 | Sensitivity to changes |
| Contour Area | 10000 | Minimum size for detection |
| Blur Kernel | (21, 21) | Noise reduction level |
Conclusion
This motion detector uses OpenCV's background subtraction and contour detection to identify movement. Adjust the threshold and contour area parameters to fine-tune sensitivity for your specific use case.
Advertisements
