A comprehensive computer vision project implementing state-of-the-art segmentation models for wheat head detection and segmentation in field images. This project explores both SAM (Segment Anything Model) fine-tuning and YOLOv8 segmentation approaches to achieve high-precision wheat head identification.
- πΎ Wheat Segmentation Project
- π Table of Contents
- π― Project Overview
- π§ Features
- π Dataset Structure
- ποΈ Project Structure
- π Getting Started
- π§ Models & Approaches
- π Model Performance
- π» Usage
- π Pre-trained Models
- π Model Export & Deployment
- π Results
- π οΈ Technical Details
- π References
- π₯ Contributing
- π License
This project addresses the challenge of automated wheat head detection and segmentation in agricultural field images. Accurate wheat head counting and segmentation is crucial for:
- Yield Estimation: Predicting crop yield based on wheat head density
- Agricultural Research: Analyzing wheat variety performance
- Precision Agriculture: Optimizing farming practices through computer vision
- Automated Monitoring: Real-time crop assessment using drones or field cameras
- β Dual Model Approach: Implementation of both SAM and YOLOv8 for comprehensive comparison
- β High-Quality Dataset: 1000 annotated wheat field images with precise segmentation masks
- β Multiple Model Variants: YOLOv8m and YOLOv8l implementations for different performance requirements
- β ONNX Export: Optimized models for production deployment
- β Comprehensive Training: Complete training pipelines with visualization and metrics
- β Real-time Inference: Fast inference capabilities for practical applications
data/
βββ train/
β βββ images/ # 1000 wheat field images (.jpg)
β βββ masks/ # 1000 corresponding segmentation masks (.png)
βββ test/ # 10 test images for evaluation
βββ 2fd875eaa.jpg
βββ 348a992bb.jpg
βββ ... (8 more test images)
Dataset Specifications:
- Training Images: 1000 high-resolution wheat field photographs
- Image Format: JPG (RGB)
- Mask Format: PNG (Binary masks)
- Image Resolution: Resized to 256Γ256 for SAM, 640Γ640 for YOLO
- Annotation Quality: Pixel-perfect segmentation masks for wheat heads
Wheat-Segmentation-1/
βββ data/ # Dataset directory
βββ SAM/ # SAM model implementation
β βββ fine-tune-sam.ipynb # SAM fine-tuning notebook
β βββ model.pth # Trained SAM model weights
βββ YOLO/ # YOLO model implementations
β βββ yolo8m/ # YOLOv8 Medium variant
β β βββ train-yolov8m-seg.ipynb
β β βββ wheat_segmentation_model.onnx
β β βββ runs/ # Training results and metrics
β βββ yolov8l/ # YOLOv8 Large variant
β βββ train-yolov8l-seg.ipynb
β βββ runs/ # Training results and metrics
βββ README.md # This file
- Python 3.7+
- CUDA-compatible GPU (recommended)
- 8GB+ RAM
- 10GB+ free disk space
- Clone the repository
git clone https://github.com/your-username/Wheat-Segmentation-1.git
cd Wheat-Segmentation-1- Install dependencies
# Install PyTorch (visit pytorch.org for specific CUDA version)
pip install torch torchvision torchaudio
# Install Ultralytics for YOLOv8
pip install ultralytics==8.0.196
# Install SAM dependencies
pip install git+https://github.com/facebookresearch/segment-anything.git
pip install git+https://github.com/huggingface/transformers.git
# Additional dependencies
pip install datasets opencv-python matplotlib monai roboflow
pip install onnx onnxruntime # For model export- Verify installation
python -c "import torch; print(f'PyTorch version: {torch.__version__}')"
python -c "import ultralytics; ultralytics.checks()"Approach: Fine-tune Meta's Segment Anything Model on wheat segmentation data using bounding box prompts.
Key Features:
- Base Model:
facebook/sam-vit-large - Training Strategy: Freeze vision encoder and prompt encoder, fine-tune mask decoder only
- Loss Function: Focal Loss for handling class imbalance
- Input Resolution: 1024Γ1024 (SAM native resolution)
- Prompt Strategy: Bounding box prompts with perturbation for robustness
Training Configuration:
- Epochs: 5
- Batch Size: 4
- Optimizer: Adam (lr=1e-5)
- Device: Multi-GPU training with DataParallel
Approach: Train YOLOv8 models specifically for wheat head instance segmentation.
- Parameters: ~27M
- Speed: Balanced performance
- Use Case: General-purpose applications
- Parameters: ~46M
- Speed: Higher accuracy, slower inference
- Use Case: High-precision applications
Training Configuration:
- Epochs: 25 (YOLOv8m), 15 (YOLOv8l)
- Image Size: 640Γ640
- Batch Size: 16
- Augmentations: Mosaic, mixup, rotation, scaling
| Model | mAP50 (Box) | mAP50-95 (Box) | mAP50 (Mask) | mAP50-95 (Mask) | Speed (ms) |
|---|---|---|---|---|---|
| YOLOv8m | 96.9% | 84.6% | 96.4% | 71.4% | ~1400 |
| YOLOv8l | 96.9% | 84.3% | 96.5% | 70.8% | ~76 |
- Training Loss Reduction: From 0.45 to 0.16 over 5 epochs
- Convergence: Stable training with consistent improvement
- Segmentation Quality: High-quality masks with precise boundaries
# Navigate to SAM directory
cd SAM/
# Open and run the Jupyter notebook
jupyter notebook fine-tune-sam.ipynbThe SAM training process includes:
- Data loading and preprocessing
- Bounding box prompt generation
- Model fine-tuning with Focal Loss
- Visualization of results
# For YOLOv8m
cd YOLO/yolo8m/
yolo task=segment mode=train model=yolov8m-seg.pt data=path/to/data.yaml epochs=25 imgsz=640
# For YOLOv8l
cd YOLO/yolov8l/
yolo task=segment mode=train model=yolov8l-seg.pt data=path/to/data.yaml epochs=15 imgsz=640# Using PyTorch model
yolo task=segment mode=predict model=path/to/best.pt source=path/to/images conf=0.25
# Using ONNX model
yolo task=segment mode=predict model=path/to/best.onnx source=path/to/images conf=0.25from transformers import SamModel, SamProcessor
import torch
# Load the fine-tuned model
model = SamModel.from_pretrained("facebook/sam-vit-large")
model.load_state_dict(torch.load("SAM/model.pth"))
processor = SamProcessor.from_pretrained("facebook/sam-vit-large")
# Run inference with bounding box prompt
inputs = processor(image, input_boxes=[[bbox]], return_tensors="pt")
outputs = model(**inputs)| Model | Type | Size | Location | Performance |
|---|---|---|---|---|
| SAM Fine-tuned | PyTorch | ~2.4GB | SAM/model.pth |
High-quality masks |
| YOLOv8m | PyTorch | ~52MB | YOLO/yolo8m/runs/segment/train/weights/best.pt |
mAP50: 96.9% |
| YOLOv8l | PyTorch | ~88MB | YOLO/yolov8l/runs/segment/train3/weights/best.pt |
mAP50: 96.9% |
| YOLOv8m | ONNX | ~105MB | YOLO/yolo8m/wheat_segmentation_model.onnx |
Production-ready |
| YOLOv8l | ONNX | ~175MB | YOLO/yolov8l/runs/segment/train3/weights/best.onnx |
Production-ready |
- For Research/Experimentation: Use SAM fine-tuned model for highest quality masks
- For Real-time Applications: Use YOLOv8m ONNX model for balanced speed/accuracy
- For Maximum Accuracy: Use YOLOv8l PyTorch model
- For Production Deployment: Use ONNX versions for cross-platform compatibility
# Export YOLOv8 to ONNX
from ultralytics import YOLO
model = YOLO("path/to/best.pt")
model.export(format="onnx", dynamic=False)- Local Inference: Direct PyTorch/ONNX inference
- Roboflow Deploy: Cloud-based API deployment
- Edge Deployment: ONNX Runtime for edge devices
- Docker Containers: Containerized inference services
- Precision: Models accurately identify individual wheat heads
- Boundary Quality: Sharp, precise segmentation boundaries
- Robustness: Consistent performance across different lighting conditions
- Scalability: Efficient processing of multiple wheat heads per image
- Detection Accuracy: >96% mAP50 for both YOLO variants
- Segmentation Quality: >96% mask mAP50
- Speed: Real-time inference capability with optimized models
- Generalization: Strong performance on test set
- Image Normalization: 0-1 scaling for neural networks
- Augmentation: Geometric and photometric augmentations
- Mask Processing: Binary mask conversion and validation
- Quality Control: Filtering of empty masks and corrupted data
- Mixed Precision: Automatic Mixed Precision for faster training
- Multi-GPU: DataParallel training support
- Learning Rate: Cosine annealing and warmup strategies
- Early Stopping: Patience-based training termination
- Model Fusion: Layer fusion for faster inference
- Batch Processing: Efficient batch inference
- Memory Management: Optimized memory usage
- Post-processing: Efficient NMS and mask generation
Contributions are welcome! Please feel free to submit a Pull Request. For major changes:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
πΎ Happy Wheat Segmentation!
For questions or support, please open an issue or contact the maintainers.