Datasets:
ArXiv:
License:
File size: 4,690 Bytes
c6e077b e1ac534 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | 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(
"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<header>
</header>
<img src="./GenHisDoc_class_distribution.png">
</body>
</html>
"""
)
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)
|