| name | yolo-detection |
| description | Détection d'objets avec YOLO (You Only Look Once) — YOLOv5 à YOLOv11, Ultralytics, entraînement, export, inférence, benchmarks, et pipelines. En français. |
Détection d'Objets — YOLO (You Only Look Once)
Famille YOLO : détection temps réel la plus populaire. De YOLOv5 (Ultralytics) à YOLOv11, en passant par YOLOv8, YOLO-NAS et YOLO-World.
1. Architecture Fondamentale
Principe
Image complète → Grille (S×S) → Chaque cellule prédit :
- Bounding boxes (x, y, w, h, confiance)
- Scores de classe (C probabilités)
Évolution des architectures
| Version | Année | Backbone | Head | AP50-95 (COCO) | FPS (T4) |
|---|
| YOLOv3 | 2018 | Darknet53 | FPN | 33.0 | 35 |
| YOLOv5 | 2020 | CSPDarknet | PANet | 50.7 | 140 |
| YOLOv8 | 2023 | CSPDarknet | C2f | 53.3 | 220 |
| YOLOv9 | 2024 | GELAN | | 55.6 | 200 |
| YOLOv10 | 2024 | ELAN | NMS-free | 55.5 | 230 |
| YOLOv11 | 2025 | | | 56.0+ | 250+ |
2. Installation et Setup
pip install ultralytics
git clone https://github.com/ultralytics/yolov5
cd yolov5 && pip install -r requirements.txt
pip install yolov6
pip install super-gradients
Export ONNX/TensorRT
yolo export model=yolo11n.pt format=onnx
yolo export model=yolo11n.pt format=engine device=0
yolo export model=yolo11n.pt format=openvino
yolo export model=yolo11n.pt format=coreml
3. Modèles et Prétentraînés
from ultralytics import YOLO
model = YOLO("yolo11n.pt")
model = YOLO("yolo11s.pt")
model = YOLO("yolo11m.pt")
model = YOLO("yolo11l.pt")
model = YOLO("yolo11x.pt")
model = YOLO("yolo11n-seg.pt")
model = YOLO("yolo11n-pose.pt")
model = YOLO("yolo11n-obb.pt")
model = YOLO("yolo11n-cls.pt")
4. Inférence
from ultralytics import YOLO
import cv2
model = YOLO("yolo11x.pt")
results = model("image.jpg")
results = model("video.mp4", stream=True)
results = model(0, stream=True)
results = model(
"image.jpg",
conf=0.25,
iou=0.45,
imgsz=640,
max_det=300,
device="cuda:0",
half=True,
agnostic_nms=True,
classes=[0, 2],
)
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0]
conf = float(box.conf[0])
cls = int(box.cls[0])
label = result.names[cls]
result.masks:
mask result.masks.data:
result.keypoints:
kpts result.keypoints.data:
annotated = result.plot()
annotated = result.plot(line_width=, font_size=, conf=)
Détection et Tracking
results = model.track("video.mp4", persist=True, tracker="bytetrack.yaml")
for result in results:
for box in result.boxes:
track_id = int(box.id[0]) if box.id is not None else None
5. Entraînement Personnalisé
Format de Dataset (COCO / YOLO)
dataset/
├── images/
│ ├── train/ # 80% des images
│ └── val/ # 20% des images
├── labels/
│ ├── train/ # Fichiers .txt (1 par image)
│ └── val/ # Fichiers .txt (1 par image)
└── dataset.yaml # Config
Format label YOLO (1 ligne par objet) :
<class_id> <x_center> <y_center> <width> <height>
Toutes les valeurs normalisées [0, 1] par rapport à la taille de l'image.
dataset.yaml :
path: /path/to/dataset
train: images/train
val: images/val
nc: 3
names: ['personne', 'voiture', 'vélo']
Lancement de l'Entraînement
from ultralytics import YOLO
model = YOLO("yolo11m.pt")
results = model.train(
data="dataset.yaml",
epochs=300,
patience=50,
batch=16,
imgsz=640,
optimizer="AdamW",
lr0=0.001,
lrf=0.01,
momentum=0.937,
weight_decay=0.0005,
warmup_epochs=3,
warmup_momentum=0.8,
warmup_bias_lr=0.1,
hsv_h=0.015,
hsv_s=0.7,
hsv_v=0.4,
degrees=0.0,
translate=0.1,
scale=0.5,
shear=0.0,
perspective=0.0,
flipud=0.0,
fliplr=0.5,
mosaic=1.0,
mixup=0.0,
copy_paste=,
dropout=,
label_smoothing=,
device=,
workers=,
project=,
name=,
exist_ok=,
pretrained=,
resume=,
val=,
plots=,
save_period=,
)
Résumé et Suivi
results = model.train(...)
print(results.results_dict)
print(results.best)
model.train(..., project="mon_projet", name="mon_exp", exist_ok=True)
6. Fine-Tuning et Transfer Learning
model = YOLO("yolo11m.pt")
model.model.model[0].requires_grad_(False)
for i, layer in enumerate(model.model.model[:10]):
layer.requires_grad_(False)
model.train(
data="dataset.yaml",
epochs=100,
freeze=10,
)
model.train(
data="dataset.yaml",
epochs=100,
lr0=0.0001,
warmup_epochs=1,
)
7. Export et Déploiement
model = YOLO("runs/detect/exp/weights/best.pt")
model.export(format="onnx")
model.export(format="engine")
model.export(format="openvino")
model.export(format="coreml")
model.export(format="tflite")
model.export(format="tfjs")
model.export(format="torchscript")
model.export(
format="engine",
half=True,
int8=False,
dynamic=True,
batch=1,
workspace=4,
)
### Inférence avec ONNX Runtime
```python
import onnxruntime as ort
import numpy as np
import cv2
# Charger
session = ort.InferenceSession("model.onnx")
input_name = session.get_inputs()[0].name
# Prétraitement
img = cv2.imread("image.jpg")
img = cv2.resize(img, (640, 640))
img = img.transpose(2, 0, 1) # HWC → CHW
img = np.expand_dims(img, axis=0).astype(np.float32)
img /= 255.0
# Inférence
outputs = session.run(None, {input_name: img})
# Post-traitement (décodage des boîtes YOLO)
# output[0] shape: (1, 84, 8400) pour YOLOv8
8. YOLO-World (Zero-shot)
from ultralytics import YOLO
model = YOLO("yolo_world_v2_xl_vlms.pt")
results = model.predict("image.jpg", text=["personne", "casque", "extincteur"])
model.set_classes(["voiture rouge", "camion bleu", "piéton"])
results = model("image.jpg")
9. OBB (Oriented Bounding Boxes)
model = YOLO("yolo11n-obb.pt")
model.train(data="dota8.yaml", epochs=100)
results = model("image_aerienne.jpg")
for result in results:
obb = result.obb
for box in obb:
x, y, w, h, r = box.xywhr[0]
10. Métriques et Évaluation
model = YOLO("best.pt")
metrics = model.val(
data="dataset.yaml",
batch=16,
imgsz=640,
conf=0.001,
iou=0.6,
)
print(metrics.box.map)
print(metrics.box.map50)
print(metrics.box.map75)
print(metrics.box.maps)
print(metrics.confusion_matrix)
Benchmarks
yolo benchmark model=yolo11n.pt imgsz=640 device=0
11. Intégration Pipeline
import cv2
from ultralytics import YOLO
from collections import defaultdict
import numpy as np
class DetectionPipeline:
def __init__(self, model_path="yolo11x.pt", conf=0.25):
self.model = YOLO(model_path)
self.conf = conf
self.track_history = defaultdict(list)
def process_frame(self, frame, track=False):
if track:
results = self.model.track(frame, conf=self.conf, persist=True)
else:
results = self.model(frame, conf=self.conf)
detections = []
for result in results:
if result.boxes is None:
continue
for box in result.boxes:
det = {
"bbox": box.xyxy[0].tolist(),
"conf": float(box.conf[0]),
"class": int(box.cls[0]),
"label": result.names[(box.cls[])],
}
box. :
det[] = (box.[])
detections.append(det)
detections, results[].plot() results frame
():
cap = cv2.VideoCapture(video_path)
out =
output_path:
fourcc = cv2.VideoWriter_fourcc(*)
fps = (cap.get(cv2.CAP_PROP_FPS))
w = (cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = (cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = cv2.VideoWriter(output_path, fourcc, fps, (w, h))
cap.isOpened():
ret, frame = cap.read()
ret:
detections, annotated = .process_frame(frame, track=)
out:
out.write(annotated)
cap.release()
out:
out.release()
12. Problèmes Courants et Solutions
| Problème | Cause | Solution |
|---|
| Overfitting | Dataset trop petit | Augmentation, dropout, pretrained léger |
| Underfitting | Pas assez d'epochs | Augmenter epochs, réduire patience |
| Faux positifs | Seuil conf trop bas | Augmenter conf à 0.5+ |
| Objets manqués | Occlusion | Augmenter imgsz, mosaïque |
| Performances GPU | Batch size | Ajuster, utiliser half=True |
| Précision faible | Annotation incorrectes | Vérifier les labels, labelliser proprement |
| RAM insuffisante | Trop d'images | Réduire batch, workers |
Références