AI-Powered Plant Bloom Detection and Tracking System
BloomWatch is a comprehensive, modular Python project template for detecting and tracking plant blooming stages from image datasets using deep learning. Perfect for researchers, botanists, and AI enthusiasts working with time-lapse plant growth data.
- π¬ Research-Ready: Modular architecture perfect for experimentation and deployment
- ποΈ Production-Ready: FastAPI web service for model serving and predictions
- π Comprehensive Analytics: Built-in visualization and metrics tracking
- βοΈ Cloud Integration: AWS S3 support for large-scale dataset management
- π°οΈ NASA Data Support: Automated MODIS satellite data downloading
- π§ͺ Fully Tested: Complete pytest suite with unit test coverage
- π Interactive Notebooks: Jupyter notebooks for data exploration and experiments
- βοΈ Configurable: YAML-based configuration with Hydra/OmegaConf support
- π Temporal Analysis: Process MODIS/VIIRS time series for bloom detection
- π± Web Interface: Streamlit app for interactive result exploration
BloomWatch/
βββ π app/ # FastAPI web application
β βββ __init__.py
β βββ main.py # FastAPI app setup with lifespan management
β βββ endpoints.py # API endpoints for predictions
β βββ models.py # Pydantic models for API
βββ π configs/ # Configuration files
β βββ config.yaml # Training configuration
βββ π data/ # Data handling and preprocessing
β βββ __init__.py
β βββ dataset.py # Dataset classes
β βββ preprocessing.py # Image processing utilities
β βββ augmentations.py # Data augmentation
β βββ downloaders.py # AWS S3 integration
β βββ fetch_modis.py # NASA MODIS data fetching
βββ π models/ # Model architectures and utilities
β βββ __init__.py
β βββ baseline.py # SimpleCNN and ResNet models
β βββ advanced.py # Advanced architectures (EfficientNet, Vision Transformer)
β βββ losses.py # Custom loss functions
β βββ utils.py # Model utilities (save/load, etc.)
βββ π notebooks/ # Jupyter notebooks for experimentation
β βββ 01_data_exploration.ipynb
β βββ 02_training_experiments.ipynb
β βββ 03_model_evaluation.ipynb
βββ π tests/ # Test suite
β βββ conftest.py # Test configuration and fixtures
β βββ test_data.py # Data module tests
β βββ test_models.py # Model tests
β βββ test_utils.py # Utility tests
βββ π utils/ # Utility functions
β βββ __init__.py
β βββ config.py # Configuration management
β βββ logging_utils.py # Logging setup
β βββ metrics.py # Metrics tracking
β βββ helpers.py # General utilities
βββ π visualization/ # Visualization and plotting
β βββ __init__.py
β βββ plots.py # Training plots and confusion matrices
β βββ plot_growth_curve.py # Plant growth visualizations
β βββ interactive.py # Interactive dashboards
β βββ timelapse.py # Time-lapse animations
βββ main.py # Main training script
βββ requirements.txt # Project dependencies
βββ README.md # This file
- Python 3.8 or higher
- CUDA-compatible GPU (optional, but recommended)
-
Clone the repository
git clone https://github.com/yourusername/BloomWatch.git cd BloomWatch -
Create a virtual environment
python -m venv venv # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate
-
Install dependencies
pip install -r requirements.txt
Start with the dummy training loop to test the complete pipeline:
# Basic training with default config
python main.py
# Custom training with specific parameters
python main.py --model resnet_baseline --epochs 20 --batch_size 32 --lr 0.001
# Training with custom config file
python main.py --config configs/config.yaml --device cudaDownload MODIS vegetation index data for your region of interest:
# Download MODIS MOD13Q1 data for a bounding box
python data/fetch_modis.py --start 2022-01-01 --end 2022-12-31 --bbox "70,8,90,37"
# List available granules without downloading
python data/fetch_modis.py --start 2022-01-01 --end 2022-12-31 --bbox "70,8,90,37" --list-only
# Force re-download even if files exist
python data/fetch_modis.py --start 2022-01-01 --end 2022-12-31 --bbox "70,8,90,37" --forceLaunch the FastAPI web service for model predictions:
# Start the FastAPI server
cd app
uvicorn main:app --reload --host 0.0.0.0 --port 8000Visit http://localhost:8000/docs for interactive API documentation.
Open Jupyter notebooks for interactive experimentation:
jupyter notebook notebooks/from data.dataset import PlantBloomDataset
from models.baseline import SimpleCNN
from utils.config import ConfigManager
# Load configuration
config = ConfigManager('configs/config.yaml').get_config()
# Create dataset
dataset = PlantBloomDataset(
data_dir="path/to/data",
annotations_file="path/to/annotations.csv"
)
# Initialize model
model = SimpleCNN(num_classes=5)
print(f"Model parameters: {sum(p.numel() for p in model.parameters()):,}")import requests
# Single image prediction
response = requests.post(
"http://localhost:8000/api/v1/predict",
files={"file": open("plant_image.jpg", "rb")}
)
result = response.json()
print(f"Predicted stage: {result['predicted_stage']}")from visualization.plot_growth_curve import plot_growth_curve
# Plot plant growth over time
plot_growth_curve(
time_points=[0, 7, 14, 21, 28],
bloom_scores=[0.1, 0.3, 0.7, 0.9, 0.8],
save_path="growth_curve.png"
)from data.fetch_modis import authenticate_earthdata, list_modis_granules, download_granules
# Authenticate with NASA Earthdata
if authenticate_earthdata():
# List available granules
granules = list_modis_granules(
start_date="2022-01-01",
end_date="2022-12-31",
bbox=(70, 8, 90, 37) # (west, south, east, north)
)
# Download granules
download_granules(
granules=granules,
output_dir="data/raw/MODIS"
)Run the complete test suite:
# Run all tests
pytest
# Run with coverage report
pytest --cov=. --cov-report=html
# Run specific test modules
pytest tests/test_models.py -vThe project uses YAML configuration files with OmegaConf. Modify configs/config.yaml:
# Model configuration
model:
num_classes: 5
name: "SimpleCNN"
# Training parameters
training:
epochs: 50
batch_size: 32
learning_rate: 0.001
# Data configuration
data:
image_size: [224, 224]
batch_size: 32
num_workers: 4
# AWS S3 configuration (optional)
aws:
bucket_name: "your-bloom-dataset"
region: "us-west-2"The FastAPI application provides several endpoints:
- POST
/api/v1/predict- Single image prediction - POST
/api/v1/predict/batch- Batch image predictions - POST
/api/v1/predict/url- Predict from image URL - GET
/api/v1/models- List available models - GET
/health- Health check
- SimpleCNN: Lightweight CNN for quick experimentation
- ResNetBaseline: ResNet-based architecture for better performance
- EfficientNet: Efficient convolutional networks
- Vision Transformer: Transformer-based image classification
- Attention Models: Custom attention mechanisms
- Create your model in
models/advanced.py:
class YourCustomModel(nn.Module):
def __init__(self, num_classes):
super().__init__()
# Your model implementation
def forward(self, x):
# Forward pass
return x- Update the model factory in
models/baseline.py
- Create a new dataset class in
data/dataset.py - Implement required methods:
__len__,__getitem__ - Add preprocessing in
data/preprocessing.py
Add new loss functions to models/losses.py:
class YourCustomLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, predictions, targets):
# Your loss computation
return loss- Loss curves (training/validation)
- Accuracy plots
- Confusion matrices
- Learning rate schedules
- Time-series bloom progression
- Interactive dashboards
- Time-lapse animations
- Statistical analysis
Create a Dockerfile for containerized deployment:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
CUDA Out of Memory
# Reduce batch size in config
python main.py --batch_size 16Import Errors
# Ensure you're in the project root and have activated the virtual environment
export PYTHONPATH="${PYTHONPATH}:$(pwd)"AWS Permissions
# Configure AWS credentials
aws configureNASA Earthdata Authentication
# Set up Earthdata credentials
# Visit https://urs.earthdata.nasa.gov/ to register and get credentialsProcess MODIS/VIIRS satellite data over time to detect and analyze plant bloom events:
# Basic temporal analysis
python pipelines/bloomwatch_temporal_workflow.py \
--aoi "[-122.7,37.7,-121.8,38.4]" \
--start 2023-05-01 \
--end 2023-09-30 \
--sensor MODIS \
--checkpoint outputs/models/stage2_transfer_learning_bloomwatch.pt
# Advanced analysis with scalability features
python pipelines/bloomwatch_temporal_workflow.py \
--aoi "[-122.7,37.7,-121.8,38.4]" \
--start 2023-05-01 \
--end 2023-09-30 \
--sensor MODIS \
--checkpoint outputs/models/stage2_transfer_learning_bloomwatch.pt \
--inference-mode patch \
--patch-size 64 \
--chunks "time:1,y:512,x:512" \
--write-zarr \
--apply-cloud-mask \
--create-monthly-aggregation \
--predictive-days 5Explore results interactively with the Streamlit web app:
streamlit run webapp/bloomwatch_explorer.py- Multi-Sensor Support: MODIS, VIIRS, Landsat, and Sentinel-2
- Spectral Indices: Computes NDVI, EVI, NDWI, MNDWI, FAI, MCI, NDCI, CI_cy
- Cloud/Snow Masking: Automatic masking of clouds and snow
- Temporal Analysis: Time series processing and anomaly detection
- AI Inference: Runs trained PyTorch models for bloom detection
- Interactive Visualizations: Folium maps and Plotly time series
- Scalable Processing: Dask/xarray support for large AOIs
- Predictive Modeling: Bloom onset prediction (3-7 days ahead)
- Multi-Sensor Fusion: Combines data from multiple sensors
- In-Situ Verification: Integrates ground truth measurements
BloomWatch is designed for:
- Botanical Research: Track flowering patterns across seasons
- Agricultural Monitoring: Optimize crop timing and yield prediction
- Climate Studies: Analyze blooming responses to environmental changes
- Phenology Research: Study plant life cycle timing
- Conservation: Monitor endangered plant species
- Multi-modal learning (images + environmental data)
- Real-time streaming from IoT cameras
- 3D plant reconstruction
- Mobile app for field data collection
- Integration with weather APIs
- Automated report generation
This project is licensed under the MIT License - see the LICENSE file for details.
- PyTorch team for the deep learning framework
- FastAPI developers for the excellent web framework
- The open-source community for inspiration and tools
- NASA Earthdata for providing open access to MODIS satellite data
- Project Maintainer: Viren Passi
- Email: virenpassi79@gmail.com
- GitHub: @VirenPassi
Happy Blooming! πΈ
BloomWatch - Bringing AI to the Garden