# π **Comprehensive Tutorial: Build a Folder Monitoring & Intruder Detection System in Python**
**#Python #Security #FolderMonitoring #IntruderDetection #OpenCV #FaceCapture #Automation #Windows #TaskScheduler #ComputerVision**
---
## πΉ **Table of Contents**
1. [Introduction: What Youβll Build](#introduction-what-youll-build)
2. [Project Overview & How It Works](#project-overview--how-it-works)
3. [Prerequisites & Required Libraries](#prerequisites--required-libraries)
4. [Step 1: Install Python & Required Packages](#step-1-install-python--required-packages)
5. [Step 2: Set Up the Folder to Monitor](#step-2-set-up-the-folder-to-monitor)
6. [Step 3: Detect Folder Access Using `watchdog`](#step-3-detect-folder-access-using-watchdog)
7. [Step 4: Capture Images Using OpenCV](#step-4-capture-images-using-opencv)
8. [Step 5: Save Images with Timestamps](#step-5-save-images-with-timestamps)
9. [Step 6: Ensure the Script Runs at Startup (Windows)](#step-6-ensure-the-script-runs-at-startup-windows)
10. [Step 7: Make the Script Run Continuously Until Manually Stopped](#step-7-make-the-script-run-continuously-until-manually-stopped)
11. [Step 8: Organize Output: Create a Dedicated "Captures" Folder](#step-8-organize-output-create-a-dedicated-captures-folder)
12. [Step 9: Add Logging for Debugging](#step-9-add-logging-for-debugging)
13. [Step 10: Final Full Code with Comments](#step-10-final-full-code-with-comments)
14. [Step 11: Test the System](#step-11-test-the-system)
15. [Step 12: Security & Privacy Considerations](#step-12-security--privacy-considerations)
16. [Step 13: Possible Enhancements](#step-13-possible-enhancements)
17. [Expected Output & Sample Image](#expected-output--sample-image)
18. [Summary & Final Thoughts](#summary--final-thoughts)
---
## π **1. Introduction: What Youβll Build**
In this **comprehensive, step-by-step tutorial**, you will learn how to build a **real-time folder monitoring and intruder detection system** using **Python**.
> π **Your Goal:**
> Create a **background program** that:
> - Monitors a **specific folder** on your computer.
> - **Instantly captures a photo** using the webcam **whenever someone opens that folder**.
> - Saves the photo with a **timestamp** in a secure folder.
> - Runs **automatically when Windows starts**.
> - Keeps running **until you manually stop it** (e.g., via Task Manager or a hotkey).
This is perfect for:
- Protecting sensitive folders.
- Monitoring unauthorized access.
- Learning **file system monitoring**, **OpenCV**, and **automation**.
> π‘ **No prior experience required** β just follow along!
---
## π§© **2. Project Overview & How It Works**
Hereβs how the system works:
```
+---------------------+
| Target Folder | β Monitored by watchdog
+----------+----------+
|
v
+---------------------+
| File System Event | β "Folder opened!"
+----------+----------+
|
v
+---------------------+
| OpenCV Camera | β Activates webcam
+----------+----------+
|
v
+---------------------+
| Capture Image | β Takes photo
+----------+----------+
|
v
+---------------------+
| Save to 'Captures' | β With timestamp
+---------------------+
```
The script will:
- Run in the background.
- Use `watchdog` to detect file system changes.
- Use `cv2` (OpenCV) to access the webcam.
- Save images like: `capture_2025-04-05_14-30-22.jpg`
---
## π οΈ **3. Prerequisites & Required Libraries**
Youβll need:
- **Python 3.7 or higher**
- **A webcam** (built-in or external)
- **Windows, macOS, or Linux** (this guide uses Windows)
- **Basic Python knowledge** (variables, functions, loops)
### π§ Libraries Weβll Use
| Library | Purpose |
|--------|--------|
| `watchdog` | Monitor folder for changes |
| `cv2` (OpenCV) | Access webcam and capture images |
| `os` | Work with directories and paths |
| `datetime` | Generate timestamps |
| `logging` | Log events for debugging |
| `time` | Add delays and control loop |
Install them using `pip`.
---
## π **4. Step 1: Install Python & Required Packages**
### β
Step 1.1: Install Python
1. Go to [https://www.python.org/downloads/](https://www.python.org/downloads/)
2. Download **Python 3.11** (recommended)
3. Run installer β **Check "Add Python to PATH"**
4. Click **Install Now**
### β
Step 1.2: Open Command Prompt
Press `Win + R`, type `cmd`, press Enter.
### β
Step 1.3: Install Required Packages
Run these commands:
```bash
pip install opencv-python
```
```bash
pip install watchdog
```
β
This installs:
- `opencv-python`: For webcam access.
- `watchdog`: For folder monitoring.
> β οΈ If you get permission errors, run CMD as **Administrator**.
---
## π **5. Step 2: Set Up the Folder to Monitor**
Choose a folder you want to protect.
### β
Example: Create a Test Folder
1. Open `This PC` β `C:\`
2. Create a new folder: `C:\Private`
3. Right-click β **Properties** β Note the path.
Weβll monitor this folder.
> π You can later move this to any sensitive folder (e.g., `Documents/Bank`).
---
## π **6. Step 3: Detect Folder Access Using `watchdog`**
The `watchdog` library watches for file system events like:
- File created
- File modified
- Folder opened (accessed)
Weβll detect **any access** to the folder.
### β
Create a Python Script
1. Open **Notepad** or **VS Code**
2. Save as: `folder_guard.py`
### β
Import Libraries
```python
import os
import cv2
from datetime import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import logging
import time
```
### β
Define the Folder to Monitor
```python
FOLDER_TO_WATCH = r"C:\Private" # Change this to your folder
```
> πΉ Use `r""` for raw string to avoid escape issues.
---
### β
Create Event Handler Class
```python
class FolderHandler(FileSystemEventHandler):
def on_any_event(self, event):
if event.is_directory:
if event.event_type in ['modified', 'created', 'moved']:
print(f"[ALERT] Folder accessed: {event.src_path}")
capture_image()
```
> β
`on_any_event` triggers on any change.
> β
We check if itβs a **directory event** (folder opened).
---
## πΈ **7. Step 4: Capture Images Using OpenCV**
Now, letβs write the `capture_image()` function.
```python
def capture_image():
cap = cv2.VideoCapture(0) # Open default camera
if not cap.isOpened():
logging.error("Cannot access camera.")
return
ret, frame = cap.read()
if ret:
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"capture_{timestamp}.jpg"
filepath = os.path.join("Captures", filename)
cv2.imwrite(filepath, frame)
logging.info(f"Image saved: {filepath}")
print(f"πΈ Image captured: {filename}")
else:
logging.error("Failed to capture image.")
cap.release()
cv2.destroyAllWindows()
```
### π Explanation:
- `cv2.VideoCapture(0)`: Opens the first webcam.
- `cap.read()`: Captures a frame.
- `cv2.imwrite()`: Saves the image.
- `cap.release()`: Releases the camera.
---
## πΎ **8. Step 5: Save Images with Timestamps**
We already added timestamping:
```python
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"capture_{timestamp}.jpg"
```
Example: `capture_2025-04-05_14-30-22.jpg`
This ensures **no overwriting** and easy sorting.
---
## π **9. Step 6: Organize Output: Create a Dedicated "Captures" Folder**
Letβs create the folder if it doesnβt exist.
Add this at the top of your script:
```python
# Create Captures folder if it doesn't exist
if not os.path.exists("Captures"):
os.makedirs("Captures")
print("π Created 'Captures' folder.")
```
> β
All photos will be saved in `.\Captures\`
---
## π **10. Step 7: Add Logging for Debugging**
Add logging to track whatβs happening.
```python
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("folder_guard.log"),
logging.StreamHandler()
]
)
```
Logs will be saved to `folder_guard.log` and shown in the console.
---
## π **11. Step 8: Make the Script Run Continuously Until Manually Stopped**
We need the script to **run forever** in the background.
### β
Start the Observer
```python
if __name__ == "__main__":
if not os.path.exists(FOLDER_TO_WATCH):
print(f"β Folder not found: {FOLDER_TO_WATCH}")
exit(1)
event_handler = FolderHandler()
observer = Observer()
observer.schedule(event_handler, FOLDER_TO_WATCH, recursive=False)
observer.start()
logging.info(f"Started monitoring: {FOLDER_TO_WATCH}")
print(f"π Monitoring folder: {FOLDER_TO_WATCH}")
print("Press Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
logging.info("Monitoring stopped by user.")
print("\nπ Monitoring stopped.")
observer.join()
```
> β
The script runs until you press `Ctrl+C`.
---
## βοΈ **12. Step 9: Ensure the Script Runs at Startup (Windows)**
To run automatically when Windows starts:
### β
Method: Add to Startup Folder
1. Press `Win + R`, type `shell:startup`, press Enter.
2. This opens: `C:\Users\<YourName>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup`
3. Create a **batch file** to run your script.
### β
Create `start_guard.bat`
In the startup folder, create `start_guard.bat`:
```batch
@echo off
cd /d "C:\path\to\your\script"
python folder_guard.py
```
> πΉ Replace `C:\path\to\your\script` with the real path.
### β
Hide the Console Window (Optional)
To run silently:
1. Download **Python Launcher for Windows** (if not installed).
2. Use `.pyw` extension or `pythonw`:
```batch
pythonw folder_guard.py
```
Or use a VBScript to hide the window.
---
## π§ͺ **13. Step 10: Final Full Code with Comments**
Hereβs the complete script:
```python
import os
import cv2
from datetime import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import logging
import time
# === CONFIGURATION ===
FOLDER_TO_WATCH = r"C:\Private" # Change this to your target folder
# Create Captures folder
if not os.path.exists("Captures"):
os.makedirs("Captures")
print("π Created 'Captures' folder.")
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("folder_guard.log"),
logging.StreamHandler()
]
)
# === IMAGE CAPTURE FUNCTION ===
def capture_image():
logging.info("Attempting to capture image...")
cap = cv2.VideoCapture(0)
if not cap.isOpened():
logging.error("β Cannot access camera.")
return
ret, frame = cap.read()
if ret:
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"capture_{timestamp}.jpg"
filepath = os.path.join("Captures", filename)
cv2.imwrite(filepath, frame)
logging.info(f"πΈ Image saved: {filepath}")
print(f"πΈ Image captured: {filename}")
else:
logging.error("β Failed to capture image.")
cap.release()
cv2.destroyAllWindows()
# === FOLDER EVENT HANDLER ===
class FolderHandler(FileSystemEventHandler):
def on_any_event(self, event):
if event.is_directory:
if event.event_type in ['modified', 'created', 'moved']:
logging.warning(f"π¨ Folder accessed: {event.src_path}")
print(f"π¨ Access detected! Capturing image...")
capture_image()
# === MAIN EXECUTION ===
if __name__ == "__main__":
if not os.path.exists(FOLDER_TO_WATCH):
print(f"β Folder not found: {FOLDER_TO_WATCH}")
logging.critical(f"Folder not found: {FOLDER_TO_WATCH}")
exit(1)
event_handler = FolderHandler()
observer = Observer()
observer.schedule(event_handler, FOLDER_TO_WATCH, recursive=False)
observer.start()
logging.info(f"β
Started monitoring: {FOLDER_TO_WATCH}")
print(f"π Monitoring folder: {FOLDER_TO_WATCH}")
print("Press Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
logging.info("π Monitoring stopped by user.")
print("\nπ Monitoring stopped.")
observer.join()
```
---
## βΆοΈ **14. Step 11: Test the System**
### β
Step-by-Step Test
1. Save the script as `folder_guard.py`
2. Open Command Prompt in the script folder
3. Run:
```bash
python folder_guard.py
```
4. Open the `C:\Private` folder
5. β
You should see:
```
π¨ Access detected! Capturing image...
πΈ Image captured: capture_2025-04-05_14-30-22.jpg
```
6. Check the `Captures` folder β the image should be there.
> β
Works even if the script window is minimized.
---
## π **15. Step 12: Security & Privacy Considerations**
### β οΈ Important Notes
| Concern | Recommendation |
|-------|----------------|
| **Legal Use** | Only monitor folders you own. Donβt spy on others. |
| **Webcam Light** | Most webcams have a light β intruder may notice. |
| **False Positives** | Explorer previews may trigger access. |
| **Antivirus** | May flag as suspicious β add to exceptions. |
| **Admin Rights** | May be needed for startup execution. |
> β
Use responsibly and ethically.
---
## π **16. Step 13: Possible Enhancements**
You can improve this system:
| Feature | How to Add |
|-------|-----------|
| **Email Alerts** | Use `smtplib` to send captured images |
| **Motion Detection** | Only capture if movement is detected |
| **Cloud Backup** | Upload to Google Drive or Dropbox |
| **Face Blurring** | Use OpenCV to blur faces for privacy |
| **Hotkey to Disable** | Press `F12` to pause monitoring |
| **GUI Interface** | Use `tkinter` for a control panel |
---
## πΌοΈ **17. Expected Output & Sample Image**
### π **Folder Structure After Running**
```
C:.
β folder_guard.py
β start_guard.bat
β folder_guard.log
β
ββββCaptures
β capture_2025-04-05_14-30-22.jpg
β capture_2025-04-05_15-12-01.jpg
β
ββββPrivate
(your sensitive files)
```
### π **Console Output**
```
π Created 'Captures' folder.
π Monitoring folder: C:\Private
Press Ctrl+C to stop.
2025-04-05 14:30:22 - WARNING - π¨ Folder accessed: C:\Private\
π¨ Access detected! Capturing image...
2025-04-05 14:30:22 - INFO - πΈ Image saved: Captures\capture_2025-04-05_14-30-22.jpg
```
### πΌοΈ **Sample Captured Image**
*(Since I can't capture real images, here's a simulated example)*
> π· **Image: A person sitting at a computer, captured by webcam**
> *File name: `capture_2025-04-05_14-30-22.jpg`*
> *Resolution: 640x480 (default webcam)*
*(Imagine a typical webcam snapshot showing the user's face and upper body.)*
---
## π **18. Summary & Final Thoughts**
### β
**What Youβve Built**
- A **real-time folder monitoring system**.
- An **intruder detection** tool that captures photos.
- A **background service** that runs at startup.
- A **secure logging and image-saving** system.
### β
**Key Skills Youβve Learned**
- Using `watchdog` to monitor file systems.
- Capturing images with `OpenCV`.
- Running Python scripts at Windows startup.
- Organizing output with timestamps.
- Logging for debugging and auditing.
### π¬ **Final Words**
Youβve just built a **professional-grade security tool** using just **100 lines of Python**.
> "The best security isnβt just locks β itβs awareness."
This project is not just functional β itβs a gateway to:
- **Home automation**
- **Surveillance systems**
- **AI-powered monitoring**
- **Ethical hacking tools**
---
π **Pro Tip**: Keep the script in a hidden location and protect it with permissions.
π **Share this tutorial** with anyone who wants to protect their digital privacy.
---
β
**Youβre now ready to deploy your folder guard!**
#PythonProject #FolderSecurity #IntruderDetection #OpenCV #Watchdog #Automation #ComputerVision #PrivacyTool #PythonScript #WindowsAutomation