| import csv |
| from pathlib import Path |
|
|
| import cv2 |
| from ultralytics import YOLO |
|
|
| |
| |
| |
|
|
| CLASSES_A_TRAITER = ["directionnel", "giratoire", "communes"] |
| MARGE_CROP_RATIO = 0.15 |
| IOU_DEDUP = 0.7 |
| INCLURE_CONFIANCE_LABEL = False |
|
|
| EXTENSIONS_IMAGES = (".jpg", ".jpeg", ".png") |
|
|
|
|
| |
|
|
| def nettoyer_chemin(saisie: str) -> Path: |
| """Nettoie la saisie utilisateur (retrait des guillemets).""" |
| return Path(saisie.strip("'\"")) |
|
|
|
|
| def poser_question_oui_non(message: str) -> bool: |
| """Pose une question fermée et renvoie un booléen.""" |
| reponse = input(message).strip().lower() |
| return reponse in ("o", "oui", "y", "yes") |
|
|
|
|
| def score_nettete_laplacien(image_bgr): |
| """Variance du Laplacien : plus la valeur est haute, plus l'image est nette.""" |
| gris = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) |
| return cv2.Laplacian(gris, cv2.CV_64F).var() |
|
|
|
|
| def iou(a, b): |
| x1, y1 = max(a[0], b[0]), max(a[1], b[1]) |
| x2, y2 = min(a[2], b[2]), min(a[3], b[3]) |
| inter = max(0, x2 - x1) * max(0, y2 - y1) |
| union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter |
| return inter / union if union else 0 |
|
|
|
|
| def dedupliquer(detections, iou_thresh=IOU_DEDUP): |
| """Écarte les boîtes de moindre confiance qui chevauchent une boîte déjà gardée.""" |
| gardees = [] |
| for det in sorted(detections, key=lambda d: -d["confidence"]): |
| if all(det["classe"] != g["classe"] or iou(det["box_xyxy"], g["box_xyxy"]) < iou_thresh |
| for g in gardees): |
| gardees.append(det) |
| return gardees |
|
|
|
|
| def dessiner_bboxes(image_bgr, detections): |
| """Retourne une copie de l'image avec les bboxes détectées + classe/confiance.""" |
| image_annotee = image_bgr.copy() |
| for det in detections: |
| x1, y1, x2, y2 = [int(v) for v in det["box_xyxy"]] |
| libelle = f"{det['classe']} {det['confidence']:.2f}" |
|
|
| cv2.rectangle(image_annotee, (x1, y1), (x2, y2), (0, 255, 0), 2) |
|
|
| (tw, th), _ = cv2.getTextSize(libelle, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2) |
| cv2.rectangle(image_annotee, (x1, max(0, y1 - th - 6)), (x1 + tw + 4, y1), (0, 255, 0), -1) |
| cv2.putText(image_annotee, libelle, (x1 + 2, max(th, y1 - 4)), |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2) |
|
|
| return image_annotee |
|
|
|
|
| def generer_csv(): |
| |
| |
| |
| modele_path = nettoyer_chemin(input("Chemin vers le modèle (.pt) : ")) |
| |
| |
| raw_imgsz = input("Taille d'image imgsz (défaut: 1024) : ").strip() |
| imgsz = int(raw_imgsz) if raw_imgsz.isdigit() else 1024 |
|
|
| raw_conf = input("Indice de confiance minimal conf (défaut: 0.20) : ").strip() |
| try: |
| conf_min = float(raw_conf) |
| except ValueError: |
| conf_min = 0.20 |
|
|
| dossier_photos = nettoyer_chemin(input("Chemin vers le dossier des images : ")) |
| dossier_crops = nettoyer_chemin(input("Chemin vers le dossier de sortie des crops : ")) |
| csv_sortie = nettoyer_chemin(input("Chemin vers le fichier CSV de sortie : ")) |
|
|
| |
| sauver_labels = poser_question_oui_non("Exporter les fichiers labels .txt ? (o/n) : ") |
| dossier_labels = None |
| if sauver_labels: |
| dossier_labels = nettoyer_chemin(input("Chemin vers le dossier de sortie des labels .txt : ")) |
| dossier_labels.mkdir(parents=True, exist_ok=True) |
|
|
| |
| sauver_images_annotees = poser_question_oui_non("Sauvegarder les images annotées avec BBOX ? (o/n) : ") |
| dossier_images_annotees = None |
| if sauver_images_annotees: |
| dossier_images_annotees = nettoyer_chemin(input("Chemin vers le dossier de sortie des images annotées : ")) |
| dossier_images_annotees.mkdir(parents=True, exist_ok=True) |
|
|
| print("-" * 50) |
|
|
| dossier_crops.mkdir(parents=True, exist_ok=True) |
| csv_sortie.parent.mkdir(parents=True, exist_ok=True) |
|
|
| modele = YOLO(str(modele_path)) |
| noms_classes = modele.names |
| id_par_nom = {nom: cid for cid, nom in noms_classes.items()} |
|
|
| photos = [p for p in dossier_photos.iterdir() if p.suffix.lower() in EXTENSIONS_IMAGES] |
| print(f"\n{len(photos)} photos trouvées dans {dossier_photos}") |
| print(f"Paramètres utilisés : imgsz={imgsz}, conf={conf_min}\n") |
|
|
| lignes_csv = [] |
|
|
| for photo_path in photos: |
| resultats = modele.predict( |
| source=str(photo_path), imgsz=imgsz, conf=conf_min, verbose=False |
| )[0] |
|
|
| image_cv = cv2.imread(str(photo_path)) |
| hauteur_image_px, largeur_image_px = image_cv.shape[:2] |
| photo_id = photo_path.stem |
|
|
| |
| detections_brutes = [] |
| for box in resultats.boxes: |
| classe_id = int(box.cls[0]) |
| nom_classe = noms_classes[classe_id] |
| if nom_classe not in CLASSES_A_TRAITER: |
| continue |
| detections_brutes.append({ |
| "classe": nom_classe, |
| "confidence": float(box.conf[0]), |
| "box_xyxy": [round(v, 1) for v in box.xyxy[0].tolist()], |
| }) |
|
|
| nb_avant = len(detections_brutes) |
|
|
| |
| detections = dedupliquer(detections_brutes) |
| nb_apres = len(detections) |
| if nb_avant != nb_apres: |
| print(f" ~ {photo_id} : {nb_avant - nb_apres} doublon(s) écarté(s) " |
| f"({nb_avant} -> {nb_apres})") |
|
|
| |
| nb_detections_gardees = 0 |
| lignes_label_yolo = [] |
|
|
| for i, det in enumerate(detections): |
| x1, y1, x2, y2 = det["box_xyxy"] |
| nom_classe = det["classe"] |
| largeur_box = x2 - x1 |
| hauteur_box = y2 - y1 |
|
|
| if sauver_labels: |
| x_centre_norm = ((x1 + x2) / 2) / largeur_image_px |
| y_centre_norm = ((y1 + y2) / 2) / hauteur_image_px |
| largeur_norm = largeur_box / largeur_image_px |
| hauteur_norm = hauteur_box / hauteur_image_px |
| classe_id = id_par_nom[nom_classe] |
|
|
| ligne = f"{classe_id} {x_centre_norm:.6f} {y_centre_norm:.6f} {largeur_norm:.6f} {hauteur_norm:.6f}" |
| if INCLURE_CONFIANCE_LABEL: |
| ligne += f" {det['confidence']:.4f}" |
| lignes_label_yolo.append(ligne) |
|
|
| marge_x = largeur_box * MARGE_CROP_RATIO |
| marge_y = hauteur_box * MARGE_CROP_RATIO |
| x1_m = max(0, int(x1 - marge_x)) |
| y1_m = max(0, int(y1 - marge_y)) |
| x2_m = min(largeur_image_px, int(x2 + marge_x)) |
| y2_m = min(hauteur_image_px, int(y2 + marge_y)) |
|
|
| crop = image_cv[y1_m:y2_m, x1_m:x2_m] |
| if crop.size == 0: |
| print(f" ! crop vide ignoré : {photo_id} détection {i}") |
| continue |
|
|
| nom_crop = f"{photo_id}_{nom_classe}_{i}.jpg" |
| chemin_crop = dossier_crops / nom_crop |
| cv2.imwrite(str(chemin_crop), crop) |
|
|
| score = score_nettete_laplacien(crop) |
| x_centre_box_px = (x1 + x2) / 2 |
|
|
| lignes_csv.append({ |
| "photo_id": photo_id, |
| "chemin_image": str(photo_path), |
| "chemin_crop_panonceau": str(chemin_crop), |
| "classe_visuelle": nom_classe, |
| "x_centre_box_px": round(x_centre_box_px, 1), |
| "largeur_image_px": largeur_image_px, |
| "hauteur_box_px": round(hauteur_box, 1), |
| "score_nettete": round(score, 2), |
| }) |
| nb_detections_gardees += 1 |
|
|
| if sauver_labels: |
| chemin_label = dossier_labels / f"{photo_id}.txt" |
| chemin_label.write_text("\n".join(lignes_label_yolo), encoding="utf-8") |
|
|
| |
| if sauver_images_annotees and nb_detections_gardees > 0: |
| image_annotee = dessiner_bboxes(image_cv, detections) |
| chemin_image_annotee = dossier_images_annotees / f"{photo_id}_annotee.jpg" |
| cv2.imwrite(str(chemin_image_annotee), image_annotee) |
|
|
| print(f"{photo_id} : {nb_detections_gardees} détection(s) gardée(s)") |
|
|
| if not lignes_csv: |
| print("\n⚠️ Aucune détection acquise.") |
| return |
|
|
| with open(csv_sortie, "w", newline="", encoding="utf-8") as f: |
| writer = csv.DictWriter(f, fieldnames=lignes_csv[0].keys()) |
| writer.writeheader() |
| writer.writerows(lignes_csv) |
|
|
| print(f"\n{len(lignes_csv)} détections écrites dans {csv_sortie}") |
|
|
|
|
| if __name__ == "__main__": |
| generer_csv() |