import random import os import numpy as np import glob import matplotlib.pyplot as plt from collections import Counter from PIL import Image, ImageDraw, ImageFont from tqdm import tqdm from ultralytics.utils.plotting import Annotator, colors images_path = "./images" labels_path = "./labels" images = glob.glob(os.path.join(images_path, "*.jpg")) + \ glob.glob(os.path.join(images_path, "*.JPG")) label_map = { 0: "Illustration", 1: "Initial", 2: "Ornament", 3: "Stamp", 4: "Table", } output_dir = "./generated_html" if os.path.isdir(output_dir): print(f"{output_dir} existe déjà") else: os.mkdir(output_dir) annotations_dir = "./annotations" if os.path.isdir(annotations_dir): print(f"{annotations_dir} existe déjà") else: os.mkdir(annotations_dir) def classes_visualisation(labels_path: str, label_map: dict, output_dir: str): total_files = 0 total_labels = [] for filename in os.listdir(labels_path): if not filename.endswith(".txt"): continue total_files += 1 input_path = os.path.join(labels_path, filename) with open(input_path, "r") as f: lines = f.readlines() for line in lines: parts = line.strip().split() if not parts: continue label = int(parts[0]) total_labels.append(label) counts = Counter(total_labels) labels = [label_map[k] for k in counts.keys()] values = list(counts.values()) total_count = sum(values) # Fonction pour afficher pourcentage + valeur absolue dans chaque part def make_autopct(values): def my_autopct(pct): absolute = int(round(pct / 100.0 * sum(values))) return f"{pct:.1f}%\n({absolute})" return my_autopct plt.figure(figsize=(7, 7)) plt.pie( values, labels=labels, autopct=make_autopct(values), textprops={"fontsize": 9}, ) plt.title( f"GenHisDoc classes distribution\n" f"Total files: {total_files} | Total labels: {total_count}" ) # Légende avec le détail des effectifs par classe legend_labels = [f"{lab} (n={val})" for lab, val in zip(labels, values)] plt.legend( legend_labels, title="Classes", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1), ) plt.tight_layout() plt.savefig( os.path.join(output_dir, "GenHisDoc_class_distribution.png"), bbox_inches="tight", ) plt.close() with open(f"{output_dir}/index.html", "w") as f: f.write( """
""" ) def draw_yolo_annotations(image_path: str, label_path: str, label_map: dict) -> Image.Image | None: """Dessine les bounding boxes YOLO sur l'image et retourne une PIL Image.""" if not os.path.exists(image_path): print(f"Image introuvable : {image_path}") return None if not os.path.exists(label_path): print(f"Label introuvable : {label_path}") return None img = np.array(Image.open(image_path).convert("RGB")) h, w = img.shape[:2] annotator = Annotator(img, line_width=2) with open(label_path, "r") as f: for line in f: parts = line.strip().split() if len(parts) < 5: continue cls_id = int(parts[0]) cx, cy, bw, bh = map(float, parts[1:5]) # Conversion YOLO (normalisé) → pixels (x1, y1, x2, y2) x1 = int((cx - bw / 2) * w) y1 = int((cy - bh / 2) * h) x2 = int((cx + bw / 2) * w) y2 = int((cy + bh / 2) * h) label = label_map.get(cls_id, str(cls_id)) annotator.box_label([x1, y1, x2, y2], label=label, color=colors(cls_id, True)) result = annotator.result() return Image.fromarray(result) def controle(label_map: dict): images_dir = images_path labels_dir = labels_path identifier_list = [] annotations_crées = 0 annotations_ignorées = 0 print("génération des annotations") for filename in tqdm(os.listdir(labels_dir)): if not filename.endswith(".txt"): continue identifier = filename.replace(".txt", "") identifier_list.append(identifier) output_path = os.path.join(annotations_dir, f"{identifier}.jpg") image = draw_yolo_annotations( os.path.join(images_dir, f"{identifier}.jpg"), os.path.join(labels_dir, f"{identifier}.txt"), label_map, ) if image is None: annotations_ignorées += 1 continue if not os.path.isfile(output_path): image.save(output_path) annotations_crées += 1 else: annotations_ignorées += 1 print(f"Annotations créées : {annotations_crées}") print(f"Annotations ignorées : {annotations_ignorées}") classes_visualisation(labels_path, label_map, output_dir) controle(label_map)