YOLOv12 Eyes Detection Model

Una soluzione avanzata per la detection degli occhi utilizzando YOLOv12 e dataset custom da HuggingFace

Dataset YOLO License


📋 Summary

Questo progetto implementa un modello di object detection specializzato per l'identificazione e localizzazione degli occhi in immagini e video, basato sull'architettura YOLOv12 (You Only Look Once version 12) di Ultralytics. Il modello è addestrato su un dataset custom di high-quality disponibil su HuggingFace e offre prestazioni eccellenti per applicazioni di computer vision.

✨ Caratteristiche Principali

  • 🎯 Detection accurata degli occhi con alta precisione e recall
  • 🚀 Architettura YOLOv12 all'avanguardia per object detection
  • 📊 Pipeline completa di training, validazione e test
  • 🎥 Predizioni multi-modalità: immagini, video, webcam in tempo reale
  • ⚙️ Configurazione flessibile tramite file YAML
  • 📈 Monitoraggio avanzato con WandB integration
  • 🔧 Design modulare per facile personalizzazione
  • 💾 Output strutturato con salvataggio automatico dei risultati

🎯 Model Details

Model Description

Il modello implementa una rete neurale convoluzionale per la detection degli occhi basata su YOLOv12, ottimizzata per:

  • Single-class detection: riconosce esclusivamente occhi
  • Real-time processing: suitable for live video streams
  • High accuracy: precision e recall elevati per applicazioni critiche
  • Robust performance: generalizza bene su diverse condizioni di illuminazione

Architecture

  • Base Model: YOLOv12n (versione nano per performance ottimali)
  • Framework: Ultralytics YOLOv12
  • Input Size: 640x640 pixels (configurabile)
  • Output: Bounding boxes con confidence scores per detection degli occhi
  • Device Support: CPU, CUDA, con supporto mixed precision

Training Configuration

training:
  epochs: 100
  batch_size: 16
  img_size: 640
  learning_rate: 0.01
  weight_decay: 0.0005
  early_stopping:
    patience: 3
    min_delta: 0.002

Performance Metrics

Metrica Valore Atteso Descrizione
Precision > 0.85 Proporzione di veri positivi
Recall > 0.80 Capacità di rilevare tutti gli occhi
F1 Score > 0.82 Bilanciamento precision/recall
mAP@0.5 > 0.80 Mean Average Precision al 50% IoU
mAP@0.5:0.95 > 0.70 mAP su soglie IoU multiple

📊 Dataset Information

Dataset Source

Dataset: AndreaPorri/Eyes_Dataset_YOLO12

  • Provider: HuggingFace Datasets
  • Type: Custom dataset per eyes detection
  • Format: YOLO format (images + labels)
  • Split: Train/Validation/Test sets pre-divisi

Dataset Structure

eyes_dataset/
├── train/
│   ├── images/     # Training images
│   └── labels/     # YOLO format annotations
├── valid/
│   ├── images/     # Validation images  
│   └── labels/     # YOLO format annotations
└── test/
    ├── images/     # Test images
    └── labels/     # YOLO format annotations

Data Characteristics

  • Object Class: Single class "eyes"
  • Image Format: JPG, PNG supportati
  • Annotation Format: YOLO (x_center, y_center, width, height) normalizzati
  • Data Quality: High-quality annotations con accuratezza sub-pixel
  • Preprocessing: Automatico download e preprocessing via HuggingFace Hub

Augmentation Strategy

Il training include sophisticated data augmentation:

  • HSV Color Space: Hue, Saturation, Value variations
  • Geometric Transformations: Rotation, translation, scaling
  • Mosaic Augmentation: Improved training stability
  • Horizontal Flipping: Standard augmentation technique
  • Customizable Parameters: Configurabili via YAML

🚀 Usage

Quick Start

1. Environment Setup

# Clone/download del repository
git clone <repository-url>
cd yolo12-eyes-detection

# Installa dipendenze
pip install -r requirements.txt

2. Configuration

Modifica il file config.yaml con le tue preferenze:

# Configurazione WandB (opzionale)
wandb:
  project: "your-project-name"
  entity: "your-username" 
  api_key: "your-wandb-api-key"

# Configurazione Hardware
hardware:
  device: "auto"        # auto, cpu, cuda, cuda:0
  mixed_precision: true

# Parametri Training
training:
  epochs: 50            # Numero epoche
  batch_size: 8         # Batch size (ridotto per 8GB VRAM)
  img_size: 640         # Risoluzione input
  learning_rate: 0.01   # Learning rate

3. Training

Pipeline Completa (Training + Validazione + Test):

python yolo12_eyes_detection_modular.py --mode all

Solo Training:

python yolo12_eyes_detection_modular.py --mode train

Solo Test (con modello esistente):

python yolo12_eyes_detection_modular.py --config config.yaml --mode test

Inference

Single Image Prediction

python predict_eyes.py \
  --model runs/train/yolo12_eyes/weights/best.pt \
  --source test_image.jpg \
  --conf 0.5 \
  --save predicted_image.jpg

Video Processing

python predict_eyes.py \
  --model runs/train/yolo12_eyes/weights/best.pt \
  --source video.mp4 \
  --conf 0.5 \
  --save output_video.mp4

Real-time Webcam

python predict_eyes.py \
  --model runs/train/yolo12_eyes/weights/best.pt \
  --source 0 \
  --conf 0.5

Batch Processing

python predict_eyes.py \
  --model runs/train/yolo12_eyes/weights/best.pt \
  --source images_folder/ \
  --conf 0.5 \
  --save predictions/

📁 Project Structure

yolo12-eyes-detection/
├── 📄 README.md                           # Questa documentazione completa
├── 📄 config.yaml                        # Configurazione principale
├── 📄 requirements.txt                   # Dipendenze Python
├── 📄 yolo12_eyes_detection_modular.py   # Script training modulare
├── 📄 predict_eyes.py                    # Script predizioni
├── 📄 ESEMPIO_USO_SEPARATO.md            # Guide d'uso dettagliate
├── 📁 data/                              # Dataset directory
│   └── eyes_dataset/                     # Dataset estratto
│       ├── train/                        # Training set
│       ├── valid/                        # Validation set  
│       ├── test/                         # Test set
│       └── data.yaml                     # Configurazione YOLO
├── 📁 runs/                              # Training outputs
│   └── train/
│       └── yolo12_eyes/                  # Run specifico
│           ├── weights/
│           │   ├── best.pt               # Modello migliore
│           │   └── last.pt               # Ultimo checkpoint
│           ├── results.png               # Grafici risultati
│           └── confusion_matrix.png      # Matrice confusione
├── 📁 risultati_eyes_detection/          # Risultati test
│   ├── validazione_finale.txt            # Risultati validazione
│   └── test_finale.txt                   # Risultati test
└── 📁 logs/                              # Log files (opzionale)

File Descriptions

File Descrizione Uso
yolo12_eyes_detection_modular.py Script training principale con pipeline completa Training, validazione, test
predict_eyes.py Script inferenza per predizioni Detection su immagini/video/webcam
config.yaml Configurazione dettagliata del progetto Personalizzazione training/inferenza
requirements.txt Lista dipendenze Python Setup ambiente
ESEMPIO_USO_SEPARATO.md Guide d'uso dettagliate Documentazione estesa

⚙️ Configuration Options

Model Selection

Scegli la variante YOLOv12 più adatta alle tue esigenze:

model:
  size: "yolo12n.pt"    # nano: più veloce, meno accurato
  # size: "yolo12s.pt"  # small: balanced
  # size: "yolo12m.pt"  # medium: more accurate  
  # size: "yolo12l.pt"  # large: high accuracy
  # size: "yolo12x.pt"  # extra large: highest accuracy

Training Parameters

training:
  epochs: 100              # Numero epoche training
  batch_size: 16           # Batch size (riduci se OutOfMemory)
  img_size: 640            # Risoluzione input (416, 512, 640, 832)
  learning_rate: 0.01      # Learning rate iniziale
  weight_decay: 0.0005     # Regularizzazione L2
  workers: 8               # Worker threads (riduci se OMP errors)

Hardware Optimization

Per GPU con 8GB VRAM (RTX 4060):

training:
  batch_size: 8            # Ridotto per sicurezza VRAM
  workers: 2               # Ridotto per evitare OMP errors
  
hardware:
  device: "cuda:0"         # Esplicito per la GPU
  mixed_precision: true    # FP16 per risparmio memoria

Augmentation Settings

training:
  augment: true            # Abilita data augmentation
  aug_par:
    hsv_h: 0.015           # Variazione hue
    hsv_s: 0.7             # Variazione saturazione
    hsv_v: 0.4             # Variazione luminosità
    degrees: 0.0           # Rotazione massima
    translate: 0.1         # Traslazione
    scale: 0.5             # Scala
    fliplr: 0.5            # Probabilità flip orizzontale
    mosaic: 1.0            # Probabilità mosaic

📈 Monitoring & Results

WandB Integration

Il progetto si integra automaticamente con Weights & Biases per:

  • Training Monitoring: Loss curves, validation metrics
  • Model Versioning: Automatic best model tracking
  • Hyperparameter Tracking: Complete configuration logging
  • Performance Visualization: Interactive charts e graphs
  • Collaboration: Easy sharing e comparison

Setup WandB:

  1. Registrati su wandb.ai
  2. Ottieni API key da wandb.ai/authorize
  3. Aggiorna config.yaml con le tue credenziali

Text-based Results

I risultati vengono salvati automaticamente anche come file di testo:

# Risultati salvati in:
risultati_eyes_detection/
├── validazione_finale.txt    # Risultati validazione dettagliati
└── test_finale.txt          # Risultati test dettagliati

Formato risultati: ``` YOLOv12 EYES DETECTION - VALIDATION RESULTS

Timestamp: 2024-01-15 10:30:45 Model: YOLOv12n (best.pt) Dataset: Eyes Detection Dataset

FINAL METRICS:

Precision: 0.987654 Recall: 0.973210 F1 Score: 0.980386 mAP@0.5: 0.991234 mAP@0.5:0.95: 0.723456


### Training Artifacts

Il training produce diversi artifact:

- **best.pt**: Modello con migliori performance
- **last.pt**: Ultimo checkpoint del training
- **results.png**: Grafici di loss e metrics
- **confusion_matrix.png**: Matrice di confusione
- **F1_curve.png**: Curva F1-Score
- **PR_curve.png**: Precision-Recall curve

---

## 🔧 Advanced Features

### Custom Early Stopping

Il sistema implementa early stopping intelligente:

```yaml
training:
  custom_early_stopping: true
  early_stopping:
    patience: 3            # Epoche senza miglioramento
    min_delta: 0.002       # Miglioramento minimo (0.2%)
    print_mess: true       # Stampa messaggi di debug

Multi-Modal Validation

Validation automatica su più set:

  • Validation Set: Durante il training (ad ogni epoca)
  • Final Validation: Best model sul validation set
  • Test Set: Best model sul test set unseen

F1-Score Calculation

Calcolo automatico F1-Score durante validation:

  • Durante Training: Callback automatico per tracking
  • Final Metrics: F1 incluso nei risultati finali
  • Output: Console e file di testo

🚨 Troubleshooting

Common Issues & Solutions

1. CUDA Out of Memory

Problema: GPU memory insufficient

# Soluzione: Riduci batch size
training:
  batch_size: 4     # o 2 per sistemi con poca VRAM
  workers: 1        # Riduci workers

2. OpenMP DataLoader Worker Error

Problema: Multi-threading issues

# Aggiungi all'inizio dello script Python
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
os.environ['OMP_NUM_THREADS'] = '4'
os.environ['MKL_NUM_THREADS'] = '4'

3. Model Best Not Found

Problema: Best model non trovato durante test

# Soluzione: Esegui prima il training
python yolo12_eyes_detection_modular.py --config config.yaml --mode train

4. Dataset Download Issues

Problema: Download dataset da HuggingFace fallisce

# Soluzione: Verifica connessione internet
# Il dataset viene scaricato automaticamente da:
# https://huggingface.co/datasets/AndreaPorri/Eyes_Dataset_YOLO12

Performance Optimization

For High-End GPUs (RTX 4090+)

training:
  batch_size: 32
  workers: 12
  img_size: 832  # Maggiore risoluzione

For Low-Memory GPUs (GTX 1060 6GB)

training:
  batch_size: 4
  workers: 2
  img_size: 416  # Risoluzione ridotta

CPU-Only Training

hardware:
  device: "cpu"
  mixed_precision: false

training:
  batch_size: 2      # Batch size molto ridotto
  workers: 1         # Single thread

🔬 Technical Details

System Requirements

Minimum Requirements

  • OS: Linux, Windows, macOS
  • Python: 3.8+
  • RAM: 8GB minimum, 16GB recommended
  • GPU: Optional, CPU training supported
  • Storage: 5GB per dataset + 2GB per artifacts

Recommended Configuration

  • Python: 3.9-3.11
  • RAM: 32GB
  • GPU: RTX 4060+ (8GB+ VRAM)
  • Storage: SSD per performance ottimali

Dependencies

Il progetto utilizza un stack tecnologico moderno:

  • Deep Learning: PyTorch 2.5.1+cu121, Ultralytics 8.3.225
  • Computer Vision: OpenCV 4.12.0, Pillow 12.0.0
  • Data Processing: NumPy 2.2.6, PyYAML 6.0.3
  • Configuration: OmegaConf 2.3.0
  • Monitoring: WandB 0.22.3
  • UI/Progress: Rich 14.2.0, Tqdm 4.67.1

Architecture Details

YOLOv12 Architecture

  • Backbone: Enhanced feature extraction
  • Neck: PAN (Path Aggregation Network) con modifiche
  • Head: Detection head con anchor-free design
  • Activation: SiLU (Swish) activation functions
  • Normalization: BatchNorm con weight standardization

Training Pipeline

  1. Dataset Loading: Automatic from HuggingFace
  2. Preprocessing: Resize, normalization, augmentation
  3. Model Initialization: Pre-trained weights loading
  4. Training Loop: Gradient descent con early stopping
  5. Validation: Periodic evaluation su validation set
  6. Model Selection: Best model based su validation mAP
  7. Testing: Final evaluation su test set unseen

📊 Evaluation Results

Benchmarking

Il modello viene valutato utilizzando standard metrics:

Validation Performance

🎯 VALIDATION RESULTS (Best Model)
┏━━━━━━━━━━━━━━┳━━━━━━━━━┓
┃ Metrica      ┃ Valore  ┃
┡━━━━━━━━━━━━━━╇━━━━━━━━━┩
│ Precision    │ 0.9932  │
│ Recall       │ 0.9951  │
│ F1 Score     │ 0.9942  │
│ mAP@0.5      │ 0.9947  │
│ mAP@0.5:0.95 │ 0.8199  │
└──────────────┴─────────┘

Test Performance

🧪 TEST RESULTS (Unseen Data)
┏━━━━━━━━━━━━━━┳━━━━━━━━━┓
┃ Metrica      ┃ Valore  ┃
┡━━━━━━━━━━━━━━╇━━━━━━━━━┩
│ Precision    │ 0.9934  │
│ Recall       │ 0.9956  │
│ F1 Score     │ 0.9945  │
│ mAP@0.5      │ 0.9945  │
│ mAP@0.5:0.95 │ 0.8149  │
└──────────────┴─────────┘

Performance Analysis

Strengths

  • High Precision: >98% precision indica basso false positive rate
  • Excellent Recall: >97% recall mostra buona detection capability
  • Strong mAP@0.5: >98% su soglia IoU 50%
  • Robust Generalization: Test performance close to validation

Use Cases

  • Medical Imaging: Eye tracking, pupil detection
  • Human-Computer Interaction: Gaze-based interfaces
  • Security Systems: Liveness detection
  • Research Applications: Eye movement studies
  • Quality Control: Industrial eye inspection

🔮 Future Improvements

Planned Enhancements

Short Term

  • Multi-class Detection: Supporto per diverse parti oculari
  • 3D Eye Landmarks: Estensione per keypoint detection
  • Real-time Optimization: Model quantization per deployment
  • Web Interface: Streamlit/Gradio web app

Medium Term

  • Video Tracking: Multi-frame eye tracking
  • Occlusion Handling: Miglior detection in presenza di occlusion
  • Cross-dataset Evaluation: Test su dataset esterni
  • API Endpoint: REST API per production deployment

Long Term

  • Mobile Deployment: TFLite/CoreML optimization
  • Multi-modal Integration: Combinazione con audio per HCI
  • Federated Learning: Distributed training capability
  • Automated Pipeline: Full MLOps integration

📜 Osservazioni

  • Prestazioni Eccellenti: Se il volto si trova in posizione naturale, occhi posizionati orizzontalmente, o leggergemnte inclunati [-30°, 30°].
  • Mal Funzionamento: Non funziona bene se gli occhi sono in posizioni non naturali, come ad esempio volto ruotato 90°.

📜 License & Citations

License

Questo progetto è rilasciato sotto licenza cc-by-nc-sa-4.0.

Uso Commerciale: Il modello YOLOv12 originale è proprietà di Ultralytics. Consultare la loro licenza per uso commerciale.

Citations

Se utilizzi questo progetto, cita:

@software{yolo12_eyes_detection,
  title={YOLOv12 Eyes Detection Model},
  author={Andrea Porri},
  year={2025},
  url={https://github.com/your-username/yolo12-eyes-detection},
  note={Computer Vision model for eye detection using YOLOv12}
}


Ultimo aggiornamento: 2025-11-07
Versione: 1.0.0
Maintainer: MiniMax Agent

Downloads last month
6
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for AndreaPorri/Yolo12n_Eyes_Detection

Finetuned
(1)
this model

Dataset used to train AndreaPorri/Yolo12n_Eyes_Detection

Free AI Image Generator No sign-up. Instant results. Open Now