A FastAPI-based application for detecting and tracking fish in videos with swimming speed analysis.
- 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
- Python 3.8 or higher
- pip (Python package manager)
- Git (for cloning the repository)
# 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.txtIf 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# 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 --reloadThe API will be available at:
- API: http://localhost:8000
- Documentation: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
- Go to http://localhost:8000/docs
- Click on "POST /detect-fish-speed"
- Click "Try it out"
- Upload your video file
- Adjust parameters (optional)
- Click "Execute"
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"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")# 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.pyProcess 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": [...]
}Check API health status.
Response:
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00.000Z"
}- 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
- max_frames: Limit processing to save time and resources
- sensitivity: Adjust detection sensitivity based on your video quality
- MP4 (.mp4)
- AVI (.avi)
- MOV (.mov)
- MKV (.mkv)
- WMV (.wmv)
- Video Quality: Higher quality videos generally produce better results
- Frame Limit: Use
max_framesparameter to limit processing time for testing - Sensitivity: Start with 'medium' sensitivity and adjust based on results
- File Size: Larger files will take more time to process
-
Python Version Issues
- Ensure you're using Python 3.8 or higher
- Check with:
python --versionorpython3 --version
-
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
-
Dependency Installation Issues
- Update pip:
pip install --upgrade pip - Clear cache:
pip cache purge - Install specific versions:
pip install -r requirements.txt --force-reinstall
- Update pip:
-
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
- Check if port 8000 is available:
-
Video Upload Fails
- Verify video format is supported
- Check file size (very large files may timeout)
- Ensure video file is not corrupted
-
No Fish Detected
- Try different sensitivity settings
- Check if video has sufficient motion/contrast
- Verify video quality and lighting
-
Slow Processing
- Reduce
max_framesparameter - Use lower resolution videos
- Check system resources
- Reduce
- 400: Bad request (invalid parameters or unsupported file)
- 422: Validation error (parameter format issues)
- 500: Internal server error (processing failed)
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
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)
-
Fork and Clone
git clone <your-fork-url> cd fish-detection-api
-
Create Virtual Environment
python3 -m venv venv source venv/bin/activate # Linux/Mac # or venv\Scripts\activate # Windows
-
Install Dependencies
pip install -r requirements.txt
-
Run Development Server
uvicorn fish_detection_api:app --host 0.0.0.0 --port 8000 --reload
- EnhancedFishDetector: Core detection logic using multiple CV methods
- SimpleFishTracker: Tracks fish across frames with unique IDs
- FastAPI Application: HTTP API server with file upload handling
- Background Processing: Handles video processing in background tasks
This project is part of a fish movement analysis system.