# πŸš€ **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