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.
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 |
|---|---|
![]() |
![]() |
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.
- How It Works
- Features
- Requirements
- Installation
- Configuration
- Usage
- Project Structure
- Troubleshooting
- Ideas for Contribution
- Contributing
- Acknowledgments
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
- A square region of interest (ROI) is calculated at the center of the frame.
cv2.createBackgroundSubtractorMOG2()builds a running model of the static background and highlights anything that changes inside the ROI.- The resulting mask is thresholded and scanned for contours; any contour above a minimum area counts as motion.
- 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
sendPhotoendpoint. - A live preview window shows the feed with the tracking zone outlined at all times; press
Escto quit.
- 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.
- Python 3.6+
- A webcam, or a video file to use as input
- A Telegram bot (
Bot Token) and yourChat ID
-
Clone the repository:
git clone https://github.com/arunishrajput/motion-detection.git cd motion-detection -
Install dependencies:
pip install -r requirements.txt
Or install the libraries manually:
pip install opencv-python requests
-
Set up a Telegram bot:
- Message @BotFather, create a bot, and copy the
Bot Tokenit 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.
- Message @BotFather, create a bot, and copy the
-
Configure the script:
Open
main.pyand 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.
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. |
-
Run the script:
python main.py
-
A window titled "Motion Detection" opens, showing the live feed with the tracking zone outlined in green.
-
Whenever motion crosses that zone (and the cooldown has passed), a snapshot is sent to your Telegram chat automatically.
-
Press
Escwith the window focused to stop the script and release the camera.
motion-detection/
├── main.py # Motion detection + Telegram notification logic
├── requirements.txt # Python dependencies
├── assets/ # Preview images used in this README
└── README.md
| 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. |
- Load credentials from environment variables / a
.envfile 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.
Feel free to fork this repository, create a feature branch, and submit a pull request. Contributions, issues, and feature requests are welcome!

