Skip to content

SAURABHM6341/Poaching-Detection-Using-DL

Repository files navigation

🦌 Poaching Detection using Deep Learning and Flask

Python Flask TensorFlow License

A sophisticated web application for detecting poaching activities in wildlife images using deep learning. Built with Flask, TensorFlow, and a modern responsive UI.

Created by Society Internship Group


✨ Features

  • 🎯 Drag-and-Drop Detection: Upload single images via intuitive drag-and-drop interface
  • 📁 Batch Processing: Analyze entire folders of wildlife images at once
  • 🤖 Deep Learning Model: Pre-trained CNN model (256x256 RGB input, binary classification)
  • 📱 SMS Alerts: Automatic Twilio notifications when poachers are detected
  • 🎨 Modern UI: Light theme with animated gradients, floating blobs, and smooth transitions
  • Real-time Results: Instant predictions with confidence scores and visual indicators
  • 📊 Detailed Analytics: Probability percentages and classification confidence displayed

🚀 Quick Start

Prerequisites

  • Python 3.13 (or compatible version)
  • Windows/Linux/macOS
  • 4GB RAM minimum (8GB recommended for model loading)

Installation

  1. Clone or download this repository

    cd "C:\Users\DELL INSPIRON 3558\Desktop\SAI-II\Poaching-Detection-using-Deep-Learning-and-Flask"
  2. Install dependencies

    py -m pip install -r requirement.txt

    This installs:

    • Flask 3.1.2
    • TensorFlow-CPU 2.20.0
    • Keras 3.12.0
    • OpenCV 4.12.0
    • Twilio (for SMS alerts)
    • NumPy, Matplotlib
  3. Set up environment variables (Optional - for SMS alerts)

    Create environment variables for Twilio integration:

    $env:TWILIO_SID = "your_account_sid"
    $env:TWILIO_AUTH_TOKEN = "your_auth_token"
    $env:TWILIO_FROM = "+1234567890"
    $env:TWILIO_TO = "+0987654321"
  4. Run the application

    py app.py
  5. Access the web interface

    Open your browser and navigate to:

    http://127.0.0.1:5000
    

📖 Usage Guide

Method 1: Drag-and-Drop (Single Image)

  1. Navigate to the "Quick Detection" section
  2. Drag an image file (JPG, PNG, BMP, TIFF, WEBP) onto the drop zone
    • Or click the drop zone to select a file
  3. The app will:
    • Display image preview with loading animation
    • Preprocess the image (BGR→RGB, resize 256x256, normalize 0-1)
    • Run prediction using the trained model
    • Show result with:
      • Green alert: No poacher detected
      • ⚠️ Red alert: Poacher detected
      • Confidence percentage
      • Progress bar visualization

Method 2: Folder Processing (Batch Detection)

  1. Navigate to the "Batch Detection" section
  2. Enter the absolute path to a folder containing wildlife images:
    C:\Users\YourName\Desktop\wildlife_images
    
  3. Click "Run Detection"
  4. The app will:
    • Process all images in the folder (JPG, JPEG, PNG, BMP, TIFF)
    • Display results for each image
    • Send SMS alert if poachers are detected (if Twilio configured)
    • Show summary of detections

🏗️ Project Structure

Poaching-Detection-using-Deep-Learning-and-Flask/
├── app.py                          # Main Flask application
├── requirement.txt                 # Python dependencies
├── README.md                       # This file
├── models/
│   └── poachingdetectionVER7.h5   # Pre-trained Keras model (256x256 RGB, binary)
├── static/
│   ├── script.js                  # Client-side JavaScript (drag-drop, animations)
│   └── css/
│       └── style.css              # Light theme styling, gradients, animations
├── templates/
│   ├── index.html                 # Main UI template (Bootstrap 5.3)
│   └── backup.html                # Backup template
└── videoconversion/
    ├── converter.py               # Video to frame extraction utility
    ├── copyofconverter.py         # Alternative converter
    └── removefile.py              # Cleanup utility

🔧 Technical Details

Model Architecture

  • Input: 256x256 RGB images
  • Type: Binary classification (Poacher vs No Poacher)
  • Threshold: Probability > 0.5 = Poacher detected
  • Loading: compile=False to avoid Keras 3.x reduction errors

Image Preprocessing Pipeline

1. Load image with OpenCV (cv2.imread)
2. Convert BGRRGB (cv2.cvtColor)
3. Resize to 256x256 (cv2.resize)
4. Convert to float32 and normalize [0-1] (img.astype('float32') / 255.0)
5. Add batch dimension (np.expand_dims)
6. Predict with model

API Endpoints

GET /

  • Renders main UI template
  • Handles folder path form submissions (POST)

POST /predict-image

  • Accepts: multipart/form-data with image field
  • Validates: File type, dimensions, integrity
  • Returns: JSON response
    {
      "is_poacher": true,
      "probability": 0.87,
      "confidence": 0.87,
      "message": "⚠️ Poacher detected!",
      "filename": "wildlife_cam_001.jpg"
    }

🎨 UI Features

Light Theme Design

  • Color Scheme: Teal (#16a085) and Green (#20c997) accents
  • Font: Poppins (Google Fonts)
  • Icons: Bootstrap Icons 1.11
  • Gradients: Soft blue-to-teal background with animated floating blobs

Animations

  • Hero Section: Slide-in animations for title and subtitle
  • Floating Icons: Continuous gentle floating motion
  • Drop Zone: Hover effects with border color changes and scaling
  • Results: Pop animation with scale transform
  • Progress Bars: Smooth width transitions

Responsive Design

  • Mobile-friendly layout with Bootstrap 5.3 grid
  • Responsive font sizes and padding
  • Touch-optimized drag-and-drop

🐛 Troubleshooting

Issue: pip is not recognized

Solution: Use py -m pip install -r requirement.txt

Issue: ModuleNotFoundError: No module named 'imghdr'

Solution: Already fixed in current version (unused import removed)

Issue: ValueError: Invalid value for argument reduction='auto'

Solution: Model loads with compile=False to bypass Keras 3.x issue

Issue: TwilioRestException: Authentication Error

Solution: Set environment variables or app works without Twilio (graceful fallback)

Issue: Wrong predictions / low accuracy

Checklist:

  • ✓ Ensure images are clear and well-lit
  • ✓ Model expects 256x256 RGB images
  • ✓ Preprocessing must convert BGR→RGB (OpenCV loads BGR by default)
  • ✓ Normalization to [0-1] range is critical
  • ✓ Check if model is trained on similar wildlife camera images

Issue: Drag-and-drop not working

Checklist:

  • ✓ Check browser console for JavaScript errors
  • ✓ Ensure script.js is loaded (view page source)
  • ✓ Try clicking the drop zone to select file manually
  • ✓ Verify file extension is supported (JPG, PNG, BMP, TIFF, WEBP)

Issue: Model not loading

Checklist:

  • ✓ Verify models/poachingdetectionVER7.h5 exists
  • ✓ Check file permissions (read access required)
  • ✓ Ensure TensorFlow and Keras are correctly installed
  • ✓ Check terminal output for specific error messages

🚀 Advanced Configuration

Custom Model Path

Edit app.py line ~18:

MODEL_PATH = os.path.join(BASE_DIR, 'models', 'your_model_name.h5')

Change Detection Threshold

Edit app.py prediction logic (default: 0.5):

is_poacher = prob > 0.5  # Change to 0.6 for stricter detection

Enable Debug Mode

Edit app.py last line:

app.run(debug=True, host='0.0.0.0', port=5000)

Add Authentication

Install Flask-Login:

py -m pip install flask-login

Then add login routes and decorators to protect endpoints.


📊 Performance Optimization

Recommendations for Production

  1. Use Gunicorn/Waitress instead of Flask development server:

    py -m pip install waitress
    waitress-serve --port=5000 app:app
  2. Enable Model Caching: Already implemented via GLOBAL_MODEL

  3. Add Redis for Session Management:

    py -m pip install flask-session redis
  4. Implement Rate Limiting:

    py -m pip install flask-limiter
  5. Use CDN for Static Files: Host Bootstrap, fonts, icons on CDN


🤝 Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📜 License

This project is licensed under the MIT License - see the LICENSE file for details.


🎓 Credits

Developed by: Society Internship Group

Technologies:

  • Flask (Web Framework)
  • TensorFlow/Keras (Deep Learning)
  • OpenCV (Image Processing)
  • Bootstrap 5 (UI Framework)
  • Twilio (SMS Notifications)

📞 Support

For issues, questions, or contributions:

  • Open an issue on GitHub
  • Contact: Society Internship Group

🔮 Future Enhancements

  • Real-time video stream analysis
  • Multi-class detection (different animal species)
  • Heat map visualization of detection regions
  • User authentication and role-based access
  • Historical analytics dashboard
  • Export detection reports as PDF
  • Integration with wildlife monitoring systems
  • Mobile app (iOS/Android)
  • Docker containerization
  • Cloud deployment (AWS/Azure/GCP)

Made with ❤️ by Society Internship Group

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •