GrechnikDataset / train_valid_test_creation.py
Paradise151's picture
Create train_valid_test_creation.py
b107b3c verified
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 файл, указав правильное количество и названия ваших классов. !!!")