File size: 6,606 Bytes
b107b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import shutil
import random

from google.colab import drive
drive.mount('/content/drive')

# 0. Программа для разбиения датасета на три выборки: тренировочную, валидационную и тестовую. seed = 42 для воспроизводимости.
# 1. Выполнено в google collab!
# 2. В папке labels есть файл classes (создаётся при разметке в labellmg). Его удали!!




# --- Настройка путей ---
# Папка, где находятся все ваши изображения после разметки
source_images_dir = '/content/drive/My Drive/dataset/grechka'
# Папка, где находятся все ваши .txt файлы аннотаций после разметки
source_labels_dir = '/content/drive/My Drive/dataset/labels'

# Папка, куда будет создан новый датасет в структуре YOLO
destination_base_dir = '/content/drive/My Drive/yolo_grechka_dataset'

# --- Настройка соотношений разбивки ---
train_ratio = 0.8  # 80% для тренировки
val_ratio = 0.15 # 15% для валидации
test_ratio = 0.05  # 5% для теста (убедитесь, что сумма равна 1.0)

# --- Создание структуры папок YOLO ---
os.makedirs(os.path.join(destination_base_dir, 'images', 'train'), exist_ok=True)
os.makedirs(os.path.join(destination_base_dir, 'images', 'val'), exist_ok=True)
os.makedirs(os.path.join(destination_base_dir, 'images', 'test'), exist_ok=True)
os.makedirs(os.path.join(destination_base_dir, 'labels', 'train'), exist_ok=True)
os.makedirs(os.path.join(destination_base_dir, 'labels', 'val'), exist_ok=True)
os.makedirs(os.path.join(destination_base_dir, 'labels', 'test'), exist_ok=True)

# --- Получение списка всех изображений ---
# Фильтруем только файлы изображений (можно добавить другие расширения, если нужно)
image_files = [f for f in os.listdir(source_images_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp'))]

# Перемешиваем список изображений для случайного разбиения
random.seed(42) # Для воспроизводимости результатов
random.shuffle(image_files)

# --- Вычисление количества файлов для каждого набора ---
total_files = len(image_files)
train_count = int(total_files * train_ratio)
val_count = int(total_files * val_ratio)
test_count = total_files - train_count - val_count # Оставшиеся идут в тест

print(f"Всего изображений: {total_files}")
print(f"Для тренировки: {train_count}")
print(f"Для валидации: {val_count}")
print(f"Для теста: {test_count}")

# --- Разбиение и копирование файлов ---
current_index = 0

# Копирование для тренировочного набора
for i in range(train_count):
    img_file = image_files[current_index]
    base_name, ext = os.path.splitext(img_file)
    label_file = base_name + '.txt' # Имя соответствующего файла аннотации

    # Копируем изображение
    shutil.copy(os.path.join(source_images_dir, img_file), os.path.join(destination_base_dir, 'images', 'train', img_file))
    # Копируем файл аннотации (проверяем его наличие)
    if os.path.exists(os.path.join(source_labels_dir, label_file)):
         shutil.copy(os.path.join(source_labels_dir, label_file), os.path.join(destination_base_dir, 'labels', 'train', label_file))
    else:
         print(f"Внимание: Файл аннотации для {img_file} не найден в {source_labels_dir}. Изображение скопировано, но без метки.")


    current_index += 1

# Копирование для валидационного набора
for i in range(val_count):
    img_file = image_files[current_index]
    base_name, ext = os.path.splitext(img_file)
    label_file = base_name + '.txt'

    shutil.copy(os.path.join(source_images_dir, img_file), os.path.join(destination_base_dir, 'images', 'val', img_file))
    if os.path.exists(os.path.join(source_labels_dir, label_file)):
        shutil.copy(os.path.join(source_labels_dir, label_file), os.path.join(destination_base_dir, 'labels', 'val', label_file))
    else:
        print(f"Внимание: Файл аннотации для {img_file} не найден в {source_labels_dir}. Изображение скопировано, но без метки.")

    current_index += 1

# Копирование для тестового набора
for i in range(test_count):
    img_file = image_files[current_index]
    base_name, ext = os.path.splitext(img_file)
    label_file = base_name + '.txt'

    shutil.copy(os.path.join(source_images_dir, img_file), os.path.join(destination_base_dir, 'images', 'test', img_file))
    if os.path.exists(os.path.join(source_labels_dir, label_file)):
        shutil.copy(os.path.join(source_labels_dir, label_file), os.path.join(destination_base_dir, 'labels', 'test', label_file))
    else:
        print(f"Внимание: Файл аннотации для {img_file} не найден в {source_labels_dir}. Изображение скопировано, но без метки.")

    current_index += 1

print("\nРазбиение датасета завершено.")
print(f"Датасет в формате YOLO создан по пути: {destination_base_dir}")

# --- Создание placeholder data.yaml файла (нужно будет заполнить классами) ---
data_yaml_content = f"""
train: ../images/train
val: ../images/val
test: ../images/test # Опционально, если вы разбили на тест

nc: 1 # Укажите количество ваших классов
names: ['impurity'] # Укажите названия ваших классов в списке
"""

data_yaml_path = os.path.join(destination_base_dir, 'data.yaml')
with open(data_yaml_path, 'w') as f:
    f.write(data_yaml_content)

print(f"Создан placeholder data.yaml файл: {data_yaml_path}")
print("!!! ВАЖНО: Отредактируйте data.yaml файл, указав правильное количество и названия ваших классов. !!!")