File size: 2,391 Bytes
c0f2554
 
2839cb6
cb6da6a
c0f2554
 
 
 
cb6da6a
 
 
 
2839cb6
 
c0f2554
 
cb6da6a
 
c0f2554
 
 
 
2839cb6
 
 
c0f2554
2839cb6
 
 
 
 
cb6da6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2839cb6
cb6da6a
 
 
 
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
import glob
import os
import random
import shutil

# Training Yolo for Object Detection in PyTorch with Your Custom Dataset — The Simple Way
# https://medium.com/data-science/training-yolo-for-object-detection-in-pytorch-with-your-custom-dataset-the-simple-way-1aa6f56cf7d9

images_dir = "./images"
labels_dir = "./labels"
output_dir = "./dataset"

val_pct = 10   # 10% validation
test_pct = 10  # 10% test

# Récupère toutes les images (en gérant .jpg et .JPG)
images = glob.glob(os.path.join(images_dir, "*.jpg")) + \
         glob.glob(os.path.join(images_dir, "*.JPG"))

random.seed(42)  # pour un split reproductible
random.shuffle(images)

n_total = len(images)
n_val = round(n_total * val_pct / 100)
n_test = round(n_total * test_pct / 100)

val_images = images[:n_val]
test_images = images[n_val:n_val + n_test]
train_images = images[n_val + n_test:]


def copy_split(split_name, image_list):
    split_images_dir = os.path.join(output_dir, split_name, "images")
    split_labels_dir = os.path.join(output_dir, split_name, "labels")
    os.makedirs(split_images_dir, exist_ok=True)
    os.makedirs(split_labels_dir, exist_ok=True)

    copied = 0
    missing_labels = 0

    for image_path in image_list:
        filename = os.path.basename(image_path)
        identifier, ext = os.path.splitext(filename)
        label_path = os.path.join(labels_dir, identifier + ".txt")

        # Copie l'image
        shutil.copy2(image_path, os.path.join(split_images_dir, filename))

        # Copie le label correspondant, s'il existe
        if os.path.isfile(label_path):
            shutil.copy2(label_path, os.path.join(split_labels_dir, identifier + ".txt"))
            copied += 1
        else:
            print(f"Label manquant pour {filename}")
            missing_labels += 1

    return copied, missing_labels


train_copied, train_missing = copy_split("train", train_images)
val_copied, val_missing = copy_split("val", val_images)
test_copied, test_missing = copy_split("test", test_images)

print(f"\nTotal images : {n_total}")
print(f"Train : {len(train_images)} images ({len(train_images)/n_total*100:.1f}%), {train_missing} labels manquants")
print(f"Val   : {len(val_images)} images ({len(val_images)/n_total*100:.1f}%), {val_missing} labels manquants")
print(f"Test  : {len(test_images)} images ({len(test_images)/n_total*100:.1f}%), {test_missing} labels manquants")