Introduction
In this tutorial, you'll learn how to build a basic real-time surveillance monitoring system using Python and OpenCV. This system will simulate how companies like Augur are turning existing camera infrastructure into intelligent monitoring tools. You'll create a program that can detect motion and analyze video feeds from a webcam or video file.
Prerequisites
- A computer with Python 3.6 or higher installed
- Basic understanding of Python programming concepts
- OpenCV library (computer vision library)
- Optional: A webcam or video file to test with
Step-by-Step Instructions
1. Setting Up Your Environment
1.1 Install Required Libraries
First, you'll need to install OpenCV and other necessary libraries. Open your terminal or command prompt and run:
pip install opencv-python numpy
This installs OpenCV for computer vision tasks and NumPy for numerical operations.
1.2 Create a New Python File
Create a new file called surveillance_system.py in your working directory. This will be your main program file.
2. Basic Video Capture
2.1 Initialize Video Capture
Start by importing the necessary libraries and setting up video capture:
import cv2
import numpy as np
# Initialize video capture
# Use 0 for webcam, or provide path to video file
video_capture = cv2.VideoCapture(0)
# Check if camera opened successfully
if not video_capture.isOpened():
print("Error: Could not open camera.")
exit()
Why? We're initializing the video capture object to access either your webcam (0) or a video file. This is the foundation of any surveillance system.
2.2 Create Basic Loop to Display Video
Add this code to create a basic video display loop:
while True:
# Read frame from video capture
ret, frame = video_capture.read()
if not ret:
print("Error: Could not read frame.")
break
# Display the frame
cv2.imshow('Surveillance System', frame)
# Break loop on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release video capture and close windows
video_capture.release()
cv2.destroyAllWindows()
Why? This loop continuously reads frames from your video source and displays them. The 'q' key allows you to quit the program gracefully.
3. Adding Motion Detection
3.1 Create Background Subtraction
Add motion detection by implementing background subtraction:
# Initialize background subtractor
bg_subtractor = cv2.createBackgroundSubtractorMOG2()
# Store previous frame
previous_frame = None
Why? Background subtraction helps identify moving objects by comparing current frames with a learned background model.
3.2 Implement Motion Detection Logic
Replace your main loop with this enhanced version:
while True:
ret, frame = video_capture.read()
if not ret:
break
# Apply background subtraction
fg_mask = bg_subtractor.apply(frame)
# Apply morphological operations to remove noise
kernel = np.ones((5,5), np.uint8)
fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel)
# Find contours of moving objects
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw bounding boxes around detected motion
for contour in contours:
if cv2.contourArea(contour) > 500: # Filter small movements
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(frame, 'Motion Detected', (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the frame with motion detection
cv2.imshow('Surveillance System', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Why? This code identifies moving objects by comparing frames, filtering out noise, and drawing rectangles around significant movements.
4. Enhancing with Real-Time Alerts
4.1 Add Simple Alert System
Modify your code to include basic alerts:
motion_detected = False
# ... inside your main loop:
for contour in contours:
if cv2.contourArea(contour) > 500:
motion_detected = True
# Add alert logic here
print("ALERT: Motion detected!")
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.putText(frame, 'ALERT: Motion Detected', (x, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
else:
motion_detected = False
Why? This adds a simple alert mechanism that notifies when motion is detected, simulating how surveillance systems might trigger alarms.
5. Testing Your System
5.1 Test with Webcam
Run your program with a webcam connected:
python surveillance_system.py
Move around in front of the camera to see motion detection in action.
5.2 Test with Video File
Replace cv2.VideoCapture(0) with cv2.VideoCapture('path_to_your_video.mp4') to test with a video file.
Summary
In this tutorial, you've built a basic surveillance monitoring system that can capture video, detect motion, and provide visual alerts. This demonstrates the fundamental technology behind systems like those developed by Augur, which analyze existing surveillance infrastructure to provide real-time intelligence. While this is a simplified version, it shows how computer vision and motion detection can be combined to create intelligent monitoring systems that analyze existing camera networks for critical infrastructure protection.



