Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

Motion Detection with OpenCV and Telegram Notifications

A lightweight Python script that watches a webcam (or video file), detects motion inside a configurable zone using OpenCV background subtraction, and instantly sends a snapshot to a Telegram chat via the Telegram Bot API.

Python OpenCV Telegram Bot API License

Preview

The mockups below are illustrative previews of the live window and the resulting alert — generated to show the layout, not real camera captures.

Live detection window Telegram alert
Motion detection window preview Telegram notification preview

When motion is detected inside the green tracking zone, the full frame is captured and pushed to your Telegram chat with a caption, in near real time.

Table of Contents

How It Works

flowchart LR
    A[Camera / video feed] --> B[Extract centered ROI square]
    B --> C[MOG2 background subtraction]
    C --> D[Threshold + find contours]
    D --> E{Contour area >\nthreshold?}
    E -- No --> A
    E -- Yes --> F{Past cooldown\nperiod?}
    F -- No --> A
    F -- Yes --> G[Capture full frame]
    G --> H[Send photo + caption\nvia Telegram Bot API]
    H --> A
Loading
  1. A square region of interest (ROI) is calculated at the center of the frame.
  2. cv2.createBackgroundSubtractorMOG2() builds a running model of the static background and highlights anything that changes inside the ROI.
  3. The resulting mask is thresholded and scanned for contours; any contour above a minimum area counts as motion.
  4. If motion is detected and the cooldown period has elapsed, the full frame (with the ROI outlined) is JPEG-encoded and posted to the Telegram Bot API's sendPhoto endpoint.
  5. A live preview window shows the feed with the tracking zone outlined at all times; press Esc to quit.

Features

  • Real-time motion detection using OpenCV's MOG2 background subtractor.
  • Detection restricted to a configurable centered square, so motion outside the zone (e.g. a doorway in the background) doesn't trigger false alerts.
  • Instant Telegram notifications with a snapshot of the moment motion was detected.
  • Configurable startup delay, cooldown period, and detection sensitivity.
  • Works with a live webcam or a pre-recorded video file.

Requirements

  • Python 3.6+
  • A webcam, or a video file to use as input
  • A Telegram bot (Bot Token) and your Chat ID

Installation

  1. Clone the repository:

    git clone https://github.com/arunishrajput/motion-detection.git
    cd motion-detection
  2. Install dependencies:

    pip install -r requirements.txt

    Or install the libraries manually:

    pip install opencv-python requests
  3. Set up a Telegram bot:

    • Message @BotFather, create a bot, and copy the Bot Token it gives you.
    • Message @userinfobot to get your numeric Telegram Chat ID.
    • Send your bot at least one message (e.g. /start) so it's allowed to message you back.
  4. Configure the script:

    Open main.py and replace the placeholders with your own credentials:

    TELEGRAM_CHAT_ID = 'YOUR_TELEGRAM_CHAT_ID'
    TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'

    For a public repo, avoid committing real credentials — consider loading them from environment variables instead.

Configuration

All tunable settings currently live as constants at the top of main.py:

Variable Default Description
TELEGRAM_CHAT_ID 'YOUR_TELEGRAM_CHAT_ID' Destination chat for alerts.
TELEGRAM_BOT_TOKEN 'YOUR_TELEGRAM_BOT_TOKEN' Your bot's API token.
message 'Motion Detected!!' Caption sent with each snapshot.
camera 1 0 for the default webcam, another index for a secondary camera, or a path to a video file.
initial_delay_seconds 1 Grace period before detection starts (lets the camera/lighting settle).
motion_cooldown_seconds 1 Minimum time between consecutive alerts, to avoid spamming.
square_size 200 Side length (px) of the centered detection zone.
threshold (foreground mask) 50 Sensitivity of the background-subtraction mask.
Contour area threshold 100 Minimum contour area (px²) to count as motion.

Usage

  1. Run the script:

    python main.py
  2. A window titled "Motion Detection" opens, showing the live feed with the tracking zone outlined in green.

  3. Whenever motion crosses that zone (and the cooldown has passed), a snapshot is sent to your Telegram chat automatically.

  4. Press Esc with the window focused to stop the script and release the camera.

Project Structure

motion-detection/
├── main.py             # Motion detection + Telegram notification logic
├── requirements.txt    # Python dependencies
├── assets/             # Preview images used in this README
└── README.md

Troubleshooting

Symptom Likely cause
Window doesn't open / crashes immediately Wrong camera index — try 0 instead of 1, or confirm no other app is using the webcam.
No Telegram messages arrive Double-check TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID, and make sure you've messaged the bot at least once.
Too many false alerts Increase the contour area threshold or the mask threshold, or reduce lighting changes/shadows in frame.
Motion isn't detected Decrease the thresholds, or confirm the subject is actually crossing the green tracking zone (only that region is analyzed).
ModuleNotFoundError on startup Run pip install -r requirements.txt inside the environment you're using to run the script.

Ideas for Contribution

  • Load credentials from environment variables / a .env file instead of hardcoding them.
  • Make the ROI size/position and thresholds configurable via CLI flags or a config file.
  • Save detected clips locally in addition to (or instead of) sending photos.
  • Add support for multiple/non-centered detection zones.

Contributing

Feel free to fork this repository, create a feature branch, and submit a pull request. Contributions, issues, and feature requests are welcome!

Acknowledgments

About

Motion Detection using OpenCV and Send Response using Telegram Bot API

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages