Paradise151 commited on
Commit
b107b3c
·
verified ·
1 Parent(s): 4cd723a

Create train_valid_test_creation.py

Browse files
Files changed (1) hide show
  1. train_valid_test_creation.py +122 -0
train_valid_test_creation.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import random
4
+
5
+ from google.colab import drive
6
+ drive.mount('/content/drive')
7
+
8
+ # 0. Программа для разбиения датасета на три выборки: тренировочную, валидационную и тестовую. seed = 42 для воспроизводимости.
9
+ # 1. Выполнено в google collab!
10
+ # 2. В папке labels есть файл classes (создаётся при разметке в labellmg). Его удали!!
11
+
12
+
13
+
14
+
15
+ # --- Настройка путей ---
16
+ # Папка, где находятся все ваши изображения после разметки
17
+ source_images_dir = '/content/drive/My Drive/dataset/grechka'
18
+ # Папка, где находятся все ваши .txt файлы аннотаций после разметки
19
+ source_labels_dir = '/content/drive/My Drive/dataset/labels'
20
+
21
+ # Папка, куда будет создан новый датасет в структуре YOLO
22
+ destination_base_dir = '/content/drive/My Drive/yolo_grechka_dataset'
23
+
24
+ # --- Настройка соотношений разбивки ---
25
+ train_ratio = 0.8 # 80% для тренировки
26
+ val_ratio = 0.15 # 15% для валидации
27
+ test_ratio = 0.05 # 5% для теста (убедитесь, что сумма равна 1.0)
28
+
29
+ # --- Создание структуры папок YOLO ---
30
+ os.makedirs(os.path.join(destination_base_dir, 'images', 'train'), exist_ok=True)
31
+ os.makedirs(os.path.join(destination_base_dir, 'images', 'val'), exist_ok=True)
32
+ os.makedirs(os.path.join(destination_base_dir, 'images', 'test'), exist_ok=True)
33
+ os.makedirs(os.path.join(destination_base_dir, 'labels', 'train'), exist_ok=True)
34
+ os.makedirs(os.path.join(destination_base_dir, 'labels', 'val'), exist_ok=True)
35
+ os.makedirs(os.path.join(destination_base_dir, 'labels', 'test'), exist_ok=True)
36
+
37
+ # --- Получение списка всех изображений ---
38
+ # Фильтруем только файлы изображений (можно добавить другие расширения, если нужно)
39
+ image_files = [f for f in os.listdir(source_images_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp'))]
40
+
41
+ # Перемешиваем список изображений для случайного разбиения
42
+ random.seed(42) # Для воспроизводимости результатов
43
+ random.shuffle(image_files)
44
+
45
+ # --- Вычисление количества файлов для каждого набора ---
46
+ total_files = len(image_files)
47
+ train_count = int(total_files * train_ratio)
48
+ val_count = int(total_files * val_ratio)
49
+ test_count = total_files - train_count - val_count # Оставшиеся идут в тест
50
+
51
+ print(f"Всего изображений: {total_files}")
52
+ print(f"Для тренировки: {train_count}")
53
+ print(f"Для валидации: {val_count}")
54
+ print(f"Для теста: {test_count}")
55
+
56
+ # --- Разбиение и копирование файлов ---
57
+ current_index = 0
58
+
59
+ # Копирование для тренировочного набора
60
+ for i in range(train_count):
61
+ img_file = image_files[current_index]
62
+ base_name, ext = os.path.splitext(img_file)
63
+ label_file = base_name + '.txt' # Имя соответствующего файла аннотации
64
+
65
+ # Копируем изображение
66
+ shutil.copy(os.path.join(source_images_dir, img_file), os.path.join(destination_base_dir, 'images', 'train', img_file))
67
+ # Копируем файл аннотации (проверяем его наличие)
68
+ if os.path.exists(os.path.join(source_labels_dir, label_file)):
69
+ shutil.copy(os.path.join(source_labels_dir, label_file), os.path.join(destination_base_dir, 'labels', 'train', label_file))
70
+ else:
71
+ print(f"Внимание: Файл аннотации для {img_file} не найден в {source_labels_dir}. Изображение скопировано, но без метки.")
72
+
73
+
74
+ current_index += 1
75
+
76
+ # Копирование для валидационного набора
77
+ for i in range(val_count):
78
+ img_file = image_files[current_index]
79
+ base_name, ext = os.path.splitext(img_file)
80
+ label_file = base_name + '.txt'
81
+
82
+ shutil.copy(os.path.join(source_images_dir, img_file), os.path.join(destination_base_dir, 'images', 'val', img_file))
83
+ if os.path.exists(os.path.join(source_labels_dir, label_file)):
84
+ shutil.copy(os.path.join(source_labels_dir, label_file), os.path.join(destination_base_dir, 'labels', 'val', label_file))
85
+ else:
86
+ print(f"Внимание: Файл аннотации для {img_file} не найден в {source_labels_dir}. Изображение скопировано, но без метки.")
87
+
88
+ current_index += 1
89
+
90
+ # Копирование для тестового набора
91
+ for i in range(test_count):
92
+ img_file = image_files[current_index]
93
+ base_name, ext = os.path.splitext(img_file)
94
+ label_file = base_name + '.txt'
95
+
96
+ shutil.copy(os.path.join(source_images_dir, img_file), os.path.join(destination_base_dir, 'images', 'test', img_file))
97
+ if os.path.exists(os.path.join(source_labels_dir, label_file)):
98
+ shutil.copy(os.path.join(source_labels_dir, label_file), os.path.join(destination_base_dir, 'labels', 'test', label_file))
99
+ else:
100
+ print(f"Внимание: Файл аннотации для {img_file} не найден в {source_labels_dir}. Изображение скопировано, но без метки.")
101
+
102
+ current_index += 1
103
+
104
+ print("\nРазбиение датасета завершено.")
105
+ print(f"Датасет в формате YOLO создан по пути: {destination_base_dir}")
106
+
107
+ # --- Создание placeholder data.yaml файла (нужно будет заполнить классами) ---
108
+ data_yaml_content = f"""
109
+ train: ../images/train
110
+ val: ../images/val
111
+ test: ../images/test # Опционально, если вы разбили на тест
112
+
113
+ nc: 1 # Укажите количество ваших классов
114
+ names: ['impurity'] # Укажите названия ваших классов в списке
115
+ """
116
+
117
+ data_yaml_path = os.path.join(destination_base_dir, 'data.yaml')
118
+ with open(data_yaml_path, 'w') as f:
119
+ f.write(data_yaml_content)
120
+
121
+ print(f"Создан placeholder data.yaml файл: {data_yaml_path}")
122
+ print("!!! ВАЖНО: Отредактируйте data.yaml файл, указав правильное количество и названия ваших классов. !!!")