Skip to content

junction-DataVim/FishMovement-Speed

Repository files navigation

🐟 Fish Detection API

A FastAPI-based application for detecting and tracking fish in videos with swimming speed analysis.

Features

  • Enhanced Fish Detection: Uses multiple detection methods (motion detection, blob detection, contour analysis)
  • Fish Tracking: Tracks individual fish across frames with unique IDs
  • Speed Calculation: Calculates swimming speeds in pixels per second
  • REST API: Easy-to-use HTTP API for video upload and analysis
  • Configurable: Multiple sensitivity settings and processing options

Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)
  • Git (for cloning the repository)

Installation

1. Clone and Setup

# Clone the repository
git clone <your-repo-url>
cd fish-detection-api

# Create a virtual environment
python3 -m venv venv

# Activate the virtual environment
# On Linux/Mac:
source venv/bin/activate
# On Windows:
# venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Alternative Setup (If you have an existing Python environment)

If you already have a Python environment manager (like conda, pipenv, or a custom setup), you can:

# Activate your existing environment
# (replace with your environment activation command)

# Install dependencies
pip install -r requirements.txt

# Start the server
uvicorn fish_detection_api:app --host 0.0.0.0 --port 8000 --reload

2. Start the API Server

# Make the startup script executable (Linux/Mac only)
chmod +x start_api.sh

# Option 1: Use the startup script
./start_api.sh

# Option 2: Start manually
# Make sure your virtual environment is activated first
source venv/bin/activate  # Linux/Mac
# or venv\Scripts\activate  # Windows

# Then start the server
uvicorn fish_detection_api:app --host 0.0.0.0 --port 8000 --reload

The API will be available at:

3. Upload and Process Video

Using the Web Interface

  1. Go to http://localhost:8000/docs
  2. Click on "POST /detect-fish-speed"
  3. Click "Try it out"
  4. Upload your video file
  5. Adjust parameters (optional)
  6. Click "Execute"

Using curl

curl -X POST "http://localhost:8000/detect-fish-speed" \
  -H "accept: application/json" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@your_video.mp4" \
  -F "sensitivity=medium" \
  -F "max_frames=1000"

Using Python

import requests

# Upload video
with open('your_video.mp4', 'rb') as video_file:
    files = {'file': video_file}
    data = {'sensitivity': 'medium', 'max_frames': 1000}

    response = requests.post(
        'http://localhost:8000/detect-fish-speed',
        files=files,
        data=data
    )

    result = response.json()
    print(f"Average Speed: {result['detection_results']['average_speed_pixels_per_second']:.2f} px/s")

4. Test the API

# Make sure your virtual environment is activated
source venv/bin/activate  # Linux/Mac
# or venv\Scripts\activate  # Windows

# Run the test client (requires a video file in the current directory)
python test_api_client_new.py

API Endpoints

POST /detect-fish-speed

Process a video file and return fish detection results.

Parameters:

  • file: Video file (mp4, avi, mov, mkv, wmv)
  • sensitivity: Detection sensitivity - low, medium, high (default: medium)
  • max_frames: Maximum frames to process (default: 1000, max: 10000)

Response:

{
  "success": true,
  "video_info": {
    "filename": "fish_video.mp4",
    "resolution": "1920x1080",
    "fps": 30.0,
    "total_frames": 900,
    "processed_frames": 900,
    "processing_time_seconds": 45.2
  },
  "detection_results": {
    "average_speed_pixels_per_second": 12.5,
    "maximum_speed_pixels_per_second": 25.8,
    "minimum_speed_pixels_per_second": 3.2,
    "speed_standard_deviation": 5.4,
    "total_speed_measurements": 156,
    "unique_fish_detected": 3,
    "total_fish_detections": 234
  },
  "fish_data": [...]
}

GET /health

Check API health status.

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00.000Z"
}

Configuration

Detection Sensitivity

  • Low: Less sensitive, fewer false positives, may miss small fish
  • Medium: Balanced detection, good for most videos
  • High: More sensitive, catches smaller movements, may have more false positives

Processing Parameters

  • max_frames: Limit processing to save time and resources
  • sensitivity: Adjust detection sensitivity based on your video quality

Supported Video Formats

  • MP4 (.mp4)
  • AVI (.avi)
  • MOV (.mov)
  • MKV (.mkv)
  • WMV (.wmv)

Performance Tips

  1. Video Quality: Higher quality videos generally produce better results
  2. Frame Limit: Use max_frames parameter to limit processing time for testing
  3. Sensitivity: Start with 'medium' sensitivity and adjust based on results
  4. File Size: Larger files will take more time to process

Troubleshooting

Common Issues

  1. Python Version Issues

    • Ensure you're using Python 3.8 or higher
    • Check with: python --version or python3 --version
  2. Virtual Environment Issues

    • Make sure your virtual environment is activated
    • Check with: which python (should point to your venv)
    • Recreate if needed: rm -rf venv && python3 -m venv venv
  3. Dependency Installation Issues

    • Update pip: pip install --upgrade pip
    • Clear cache: pip cache purge
    • Install specific versions: pip install -r requirements.txt --force-reinstall
  4. API Not Starting

    • Check if port 8000 is available: lsof -i :8000
    • Try a different port: uvicorn fish_detection_api:app --port 8001
    • Check the terminal for error messages
  5. Video Upload Fails

    • Verify video format is supported
    • Check file size (very large files may timeout)
    • Ensure video file is not corrupted
  6. No Fish Detected

    • Try different sensitivity settings
    • Check if video has sufficient motion/contrast
    • Verify video quality and lighting
  7. Slow Processing

    • Reduce max_frames parameter
    • Use lower resolution videos
    • Check system resources

Error Codes

  • 400: Bad request (invalid parameters or unsupported file)
  • 422: Validation error (parameter format issues)
  • 500: Internal server error (processing failed)

Dependencies

The project requires the following Python packages (automatically installed with pip install -r requirements.txt):

  • FastAPI: Web framework for building APIs
  • Uvicorn: ASGI server for running FastAPI
  • OpenCV: Computer vision library for video processing
  • NumPy: Numerical computing library
  • Pandas: Data manipulation library
  • Matplotlib: Plotting library
  • Pydantic: Data validation library
  • Python-multipart: File upload handling
  • Aiofiles: Async file operations

Development

Project Structure

fish-detection-api/
├── fish_detection_api.py          # Main API application
├── requirements.txt               # Python dependencies
├── start_api.sh                  # Startup script (Linux/Mac)
├── test_api_client_new.py        # Test client
├── test_api_client.py            # Alternative test client
├── README.md                     # This file
├── venv/                         # Virtual environment (created after setup)
└── fish_results/                 # Output directory (created automatically)

Setting Up Development Environment

  1. Fork and Clone

    git clone <your-fork-url>
    cd fish-detection-api
  2. Create Virtual Environment

    python3 -m venv venv
    source venv/bin/activate  # Linux/Mac
    # or venv\Scripts\activate  # Windows
  3. Install Dependencies

    pip install -r requirements.txt
  4. Run Development Server

    uvicorn fish_detection_api:app --host 0.0.0.0 --port 8000 --reload

API Components

  1. EnhancedFishDetector: Core detection logic using multiple CV methods
  2. SimpleFishTracker: Tracks fish across frames with unique IDs
  3. FastAPI Application: HTTP API server with file upload handling
  4. Background Processing: Handles video processing in background tasks

License

This project is part of a fish movement analysis system.

About

A FastAPI-based application for detecting and tracking fish in videos with swimming speed analysis.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published