Dataset Viewer
Auto-converted to Parquet Duplicate
Search is not available for this dataset
image
imagewidth (px)
80
80
label
class label
132 classes
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
0#
12_line
12_line
12_line
23_line
23_line
23_line
23_line
23_line
23_line
23_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
34_line
4@
4@
4@
4@
4@
4@
4@
4@
4@
4@
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
5a
6accumulator
6accumulator
6accumulator
6accumulator
6accumulator
6accumulator
6accumulator
6accumulator
6accumulator
End of preview. Expand in Data Studio

Генерация датасета скрипт как есть для python 3.10, 3.12

import os
import random
import glob
import json
import numpy as np
from PIL import Image, ImageDraw

target_dataset_dir = "dataset"
icons_root = "icons"
img_size = 640
page_idx = 0  # Начальный индекс

classes_file = os.path.join(target_dataset_dir, '..', 'classes.txt')
if not os.path.exists(classes_file):
    classes_file = 'classes.txt'

if not os.path.exists(classes_file):
    # Если файла classes.txt нет, создаем его автоматически на основе папок
    classes = sorted([d for d in os.listdir(icons_root) if os.path.isdir(os.path.join(icons_root, d))])
    with open('classes.txt', 'w', encoding='utf-8') as f:
        f.write('\n'.join(classes))
else:
    with open(classes_file, 'r', encoding='utf-8') as f:
        classes = [line.strip() for line in f.readlines() if line.strip()]

# Автоматическое создание структуры папок YOLO
for split in ['train', 'val']:
    os.makedirs(os.path.join(target_dataset_dir, 'images', split), exist_ok=True)
    os.makedirs(os.path.join(target_dataset_dir, 'labels', split), exist_ok=True)


all_icons_pool = []
for cls_name in classes:
    cls_id = classes.index(cls_name)
    cls_folder = os.path.join(icons_root, cls_name)
    if os.path.exists(cls_folder):
        files = glob.glob(os.path.join(cls_folder, "*.png"))
        for f_path in files:
            all_icons_pool.append({"path": f_path, "cls_id": cls_id, "cls_name": cls_name})

# Создаем копию пула, которую превращаем в очередь гарантированного использования
guaranteed_queue = list(all_icons_pool)

# Перемешиваем обе структуры для равномерного случайного распределения классов по страницам
random.shuffle(all_icons_pool)
random.shuffle(guaranteed_queue)

total_unique_icons = len(guaranteed_queue)
print(f"Успешно инициализировано классов: {len(classes)}")
print(f"Всего уникальных иконок для гарантированного использования: {total_unique_icons}")


def generate_pure_gradient(w, h):
    """Генерирует чистый двухцветный градиент (для заливки иконок и обычного фона)"""
    c1 = np.array([random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)])
    c2 = np.array([random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)])

    base = np.zeros((h, w, 3), dtype=np.uint8)
    for y in range(h):
        mix = y / max(1, h - 1)
        base[y, :, :] = (c1 * (1 - mix) + c2 * mix).astype(np.uint8)
    return Image.fromarray(base)


def generate_bg_img(w, h):
    """Генерирует фон всего холста: в 30% случаев — шум ТВ, в 70% — градиент"""
    if random.random() < 0.30:
        if random.random() < 0.5:
            # Черно-белый шум телевизора
            noise_bw = np.random.randint(0, 256, (h, w), dtype=np.uint8)
            base = np.stack([noise_bw, noise_bw, noise_bw], axis=-1)
        else:
            # Цветной цифровой шум
            base = np.random.randint(0, 256, (h, w, 3), dtype=np.uint8)

        # Добавление горизонтальных строк сканирования кинескопа
        if random.random() < 0.7:
            draw_img = Image.fromarray(base)
            draw = ImageDraw.Draw(draw_img)
            for y in range(0, h, random.randint(4, 12)):
                shadow = random.randint(0, 50)
                draw.line([(0, y), (w, y)], fill=(shadow, shadow, shadow), width=random.randint(1, 3))
            base = np.array(draw_img)
        return Image.fromarray(base)
    else:
        return generate_pure_gradient(w, h)


def find_coeffs(pa, pb):
    """Вычисляет коэффициенты перспективной проекции для PIL transform"""
    matrix = []
    for p1, p2 in zip(pa, pb):
        matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
        matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])
    A = np.array(matrix)
    B = np.array(pb).flatten()
    res = np.linalg.lstsq(A, B, rcond=None)[0]
    return res

# Цикл продолжается, пока ХОТЯ БЫ ОДИН уникальный файл из всех папок не был использован
while len(guaranteed_queue) > 0:
    bg = generate_bg_img(img_size, img_size)

    # 80% картинок отправляем в train, 20% в val
    split = 'train' if random.random() < 0.8 else 'val'

    # Плотность упаковки холста (от 8 до 16 объектов)
    icons_to_place = random.randint(8, 16)

    yolo_labels = []
    labelme_shapes = []

    # Разбиваем холст 640x640 на виртуальную сетку ячеек 160x160 для минимизации наложений
    cells = [(x, y) for x in range(0, 640, 160) for y in range(0, 640, 160)]
    random.shuffle(cells)

    for k in range(icons_to_place):
        # ОПРЕДЕЛЯЕМ ИСТОЧНИК ИКОНКИ:
        # Если в гарантированной очереди еще есть файлы — строго берем оттуда
        if len(guaranteed_queue) > 0:
            icon_data = guaranteed_queue.pop(0)
        # Если гарантированная очередь пуста, но мы заполняем текущую страницу до конца
        elif len(all_icons_pool) > 0:
            icon_data = random.choice(all_icons_pool)
        else:
            break

        cls_id = icon_data["cls_id"]
        cls_name = icon_data["cls_name"]

        # Безопасное открытие файла
        try:
            raw_icon = Image.open(icon_data["path"]).convert("RGBA")
        except Exception as e:
            print(f"[ПРОПУСК] Не удалось открыть файл: {icon_data['path']}. Ошибка: {e}")
            continue

        icon_w, icon_h = 80, 80

        # Окрашивание черного контура иконки в градиент через альфа-маску
        icon_grad = generate_pure_gradient(icon_w, icon_h).convert("RGBA")
        _, _, _, alpha = raw_icon.split()
        colored_icon = Image.new("RGBA", (icon_w, icon_h), (0, 0, 0, 0))
        colored_icon.paste(icon_grad, (0, 0), mask=alpha)

        # Настройка аккуратной 3D-перспективы (макс. сдвиг углов — 6 пикселей)
        max_distort = 6
        quad = [
            (random.randint(0, max_distort), random.randint(0, max_distort)),
            (random.randint(0, max_distort), icon_h - random.randint(0, max_distort)),
            (icon_w - random.randint(0, max_distort), icon_h - random.randint(0, max_distort)),
            (icon_w - random.randint(0, max_distort), random.randint(0, max_distort))
        ]
        orig_quad = [(0, 0), (0, icon_h), (icon_w, icon_h), (icon_w, 0)]

        coeffs = find_coeffs(quad, orig_quad)
        colored_icon = colored_icon.transform((icon_w, icon_h), Image.Transform.PERSPECTIVE, coeffs, Image.Resampling.BICUBIC)

        # Случайное искажение пропорций (сплющивание/вытягивание по вертикали на +-10%)
        stretch_factor = random.uniform(0.90, 1.10)
        new_h = int(icon_h * stretch_factor)
        colored_icon = colored_icon.resize((icon_w, new_h), Image.Resampling.LANCZOS)

        # Небольшой случайный поворот в плоскости экрана (в пределах +-15 градусов)
        colored_icon = colored_icon.rotate(random.randint(-15, 15), expand=True, resample=Image.Resampling.BICUBIC)

        # Получаем реальные размеры объекта без учета прозрачных полей вращения
        object_bbox = colored_icon.getbbox()
        if object_bbox is None:
            continue

        obj_x1, obj_y1, obj_x2, obj_y2 = object_bbox
        real_w = obj_x2 - obj_x1
        real_h = obj_y2 - obj_y1

        icon_w, icon_h = colored_icon.size

        # Вычисление координат размещения на основе виртуальной сетки
        if k < len(cells):
            cell_x, cell_y = cells[k]
            x_min = cell_x + random.randint(0, max(1, 160 - icon_w))
            y_min = cell_y + random.randint(0, max(1, 160 - icon_h))
        else:
            x_min = random.randint(0, img_size - icon_w)
            y_min = random.randint(0, img_size - icon_h)

        # Удерживаем холст иконки строго в границах основного холста 640x640
        x_min = max(0, min(x_min, img_size - icon_w))
        y_min = max(0, min(y_min, img_size - icon_h))

        # Накладываем готовую иконку на общий фон
        bg.paste(colored_icon, (x_min, y_min), colored_icon)

        # Рассчитываем истинные координаты видимой части для разметки
        true_x_min = float(x_min + obj_x1)
        true_y_min = float(y_min + obj_y1)
        true_x_max = float(x_min + obj_x2)
        true_y_max = float(y_min + obj_y2)

        # Формирование строки разметки YOLO (нормализованные координаты)
        x_center = (true_x_min + real_w / 2) / img_size
        y_center = (true_y_min + real_h / 2) / img_size
        w_norm = real_w / img_size
        h_norm = real_h / img_size
        yolo_labels.append(f"{cls_id} {x_center:.6f} {y_center:.6f} {w_norm:.6f} {h_norm:.6f}")

        # Формирование структуры объекта для Labelme
        labelme_shapes.append({
            "label": cls_name,
            "points": [[true_x_min, true_y_min], [true_x_max, true_y_max]],
            "group_id": None,
            "shape_type": "rectangle",
            "flags": {}
        })


    if yolo_labels:
        file_id = f"synth_dense_{page_idx:05d}"
        img_filename = f"{file_id}.jpg"

        # А) Сохраняем картинку
        img_save_path = os.path.join(target_dataset_dir, 'images', split, img_filename)
        bg.convert("RGB").save(img_save_path, "JPEG", quality=95)

        # Б) Сохраняем .txt файл YOLO (в папку labels)
        txt_save_path = os.path.join(target_dataset_dir, 'labels', split, f"{file_id}.txt")
        with open(txt_save_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(yolo_labels))

        # В) Сохраняем .json файл Labelme (строго рядом с картинкой в папку images)
        labelme_json = {
            "version": "6.1.3",
            "flags": {},
            "shapes": labelme_shapes,
            "imagePath": img_filename,
            "imageData": None,
            "imageHeight": img_size,
            "imageWidth": img_size
        }
        json_save_path = os.path.join(target_dataset_dir, 'images', split, f"{file_id}.json")
        with open(json_save_path, "w", encoding="utf-8") as f:
            json.dump(labelme_json, f, ensure_ascii=False, indent=2)

        page_idx += 1


print(f"\n[ГОТОВО] Последний индекс страницы: {page_idx}.")
print(f"Все {total_unique_icons} иконок из пула успешно гарантированно обработаны.")
print(f"Результаты записаны в директорию: {os.path.abspath(target_dataset_dir)}")
Downloads last month
6