DEV Community

Nelson Cuadrado
Nelson Cuadrado

Posted on

Motion Detection Around the Fence with Python and OpenCV

Introduction

In today's connected world, the fusion of computer vision and traditional outdoor infrastructure is transforming how we monitor and protect property. One of the most effective use cases is motion detection around a fence perimeter. Leveraging Python and OpenCV, this blog post walks you through building a basic yet functional motion detection system designed for monitoring wood fences—ideal for homeowners, property managers, and even a fence company looking to offer smarter solutions to clients.

Security cameras can be expensive, and monitoring them 24/7 is neither practical nor efficient. Motion detection allows you to focus on meaningful events—movement near or around your fence. This system acts like a digital watchdog, making it highly relevant for anyone interested in smart security upgrades.

Installing Required Libraries

Make sure Python is installed, then open a terminal and install the required libraries:

pip install opencv-python numpy
Enter fullscreen mode Exit fullscreen mode

Setting Up Basic Motion Detection

Create a file called fence_monitor.py and paste the following code:

import cv2
import numpy as np
import datetime

cap = cv2.VideoCapture(0)
first_frame = None

while True:
    ret, frame = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)

    if first_frame is None:
        first_frame = gray
        continue

    frame_delta = cv2.absdiff(first_frame, gray)
    thresh = cv2.threshold(frame_delta, 25, 255, cv2.THRESH_BINARY)[1]
    thresh = cv2.dilate(thresh, None, iterations=2)
    contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        if cv2.contourArea(contour) < 1000:
            continue
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cv2.putText(frame, f"Movement at {timestamp}", (10, 20),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

    cv2.imshow("Fence Monitor", frame)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
Enter fullscreen mode Exit fullscreen mode

This code provides a real-time video feed and highlights areas where movement is detected. It's ideal for integrating into outdoor surveillance for clients exploring Wood Fence Installation Chicago IL with added technological value.

Enhancing the Fence Monitoring System

To take this further, let’s save images whenever motion is detected:

import os
if not os.path.exists("captured"):
    os.makedirs("captured")

# Add inside the contour loop
filename = f"captured/motion_{timestamp.replace(':', '-')}.jpg"
cv2.imwrite(filename, frame)
Enter fullscreen mode Exit fullscreen mode

Now, every time motion is detected, a snapshot is saved—helpful for evidence or record-keeping. This functionality is especially attractive to property owners interested in Wood Fence Installation Chicago who want peace of mind through technology.

Optional: Email Notifications with SMTP

Want to receive an email when movement is detected? Here’s a simplified example using smtplib:

import smtplib
from email.message import EmailMessage

def send_email_alert():
    msg = EmailMessage()
    msg.set_content("Motion detected near your fence.")
    msg['Subject'] = 'Fence Alert'
    msg['From'] = 'your_email@example.com'
    msg['To'] = 'recipient@example.com'

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login('your_email@example.com', 'your_password')
        smtp.send_message(msg)
Enter fullscreen mode Exit fullscreen mode

You can call send_email_alert() inside the motion detection block to notify you when activity occurs.

Using Flask for Remote Access

Want to access your camera remotely? Add Flask to create a lightweight web server:

pip install flask
Enter fullscreen mode Exit fullscreen mode
from flask import Flask, Response
app = Flask(__name__)

@app.route('/')
def video():
    def generate():
        while True:
            ret, frame = cap.read()
            if not ret:
                break
            _, buffer = cv2.imencode('.jpg', frame)
            frame_bytes = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
    return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
Enter fullscreen mode Exit fullscreen mode

This makes your webcam stream accessible over the local network or internet (with port forwarding).

Final Thoughts

Technology like this helps homeowners and small businesses enhance the security of their fences without breaking the bank. It adds incredible value for those interested in Wood Fence Installation in Chicago by offering an extra layer of protection.

Use Case for Fence Companies

Fence companies can integrate this kind of smart monitoring system as an upsell or feature in premium packages. It differentiates your service offerings and places your brand ahead of the curve. Many readers on blogs online are looking for DIY options, but professional integration is always appealing for reliability and quality assurance.

Conclusion

Python and OpenCV give us the power to modernize physical infrastructure. Whether you’re a developer experimenting with computer vision or part of a fence company looking to innovate, implementing a motion detection system is both practical and forward-thinking.

By merging traditional construction with intelligent technology, your fence can become more than a boundary—it becomes part of a smart security network.

Stay tuned for future posts where we integrate cloud storage, face detection, and AI-based threat evaluation!

Top comments (0)