Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Скриптовые языки программирования > Python
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 09.02.2025, 21:27   #51
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Хотел сделать что-бы мозаики резались блоками но получилось что полосками штрихкодов... Может кому понадобиться?
Код:
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog, messagebox
import random
import os

# Параметры
image_data = []  # Хранение данных изображений
canvas = None  # Canvas для отображения
current_flat_mosaic = None  # Хранение текущей мозаики для отображения
canvas_width = 640  # Ширина холста
canvas_height = 480  # Высота холста
update_interval = 100  # Интервал обновления в миллисекундах
is_running = False  # Флаг, указывающий, запущена ли анимация

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_paths:
        for fp in file_paths:
            img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
            image_data.append(img)  # Сохраняем изображение в массив
            image_listbox.insert(tk.END, fp)  # Добавляем путь к изображению на новую строку

def split_image(image, min_blocks=4):
    height, width, _ = image.shape
    # Генерация случайных размеров блоков
    num_blocks = random.randint(min_blocks, max(1, width))  # Случайное количество блоков
    block_width = width // num_blocks
    blocks = []

    for i in range(num_blocks):
        start_x = i * block_width
        end_x = start_x + block_width if i < num_blocks - 1 else width  # Последний блок берет оставшиеся пиксели
        block = image[:, start_x:end_x]  # Извлекаем блок
        blocks.append(block)

    return blocks

def generate_random_mosaic(images):
    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)
    flat_mosaic_blocks = []

    # Сначала собираем блоки из всех изображений
    for img in images:
        blocks = split_image(img)
        flat_mosaic_blocks.extend(blocks)

    # Перемешиваем блоки
    random.shuffle(flat_mosaic_blocks)

    # Заполняем новую мозаику из перемешанных блоков
    idx = 0
    for block in flat_mosaic_blocks:
        if idx + block.shape[1] <= flat_mosaic.shape[1]:  # Проверяем, можно ли вставить блок
            flat_mosaic[:, idx:idx + block.shape[1]] = block
            idx += block.shape[1]
        else:
            break  # Прерываем, если не помещается

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas
    if canvas is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()  # Запускаем анимацию

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)  # Генерируем новую мозаику
        update_canvas(current_flat_mosaic)  # Обновляем холст с новой мозаикой
        root.after(update_interval, run_mosaic_animation)  # Запланировать следующую итерацию

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x500")

load_image_button = tk.Button(root, text="Загрузить изображения", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

root.mainloop()

Ссылка на гитхаб -> ссылка.

Последний раз редактировалось MakarovDs; 09.02.2025 в 21:34.
MakarovDs на форуме Ответить с цитированием
Старый 09.02.2025, 23:02   #52
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Ну мне нужны не полоски а квадратик случайно вырезанных и совмещенных изображений в потоке
Код:
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
import random
import os

# Параметры
image_data = []
canvas = None
current_flat_mosaic = None
canvas_width = 640
canvas_height = 480
update_interval = 100
is_running = False

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_paths:
        for fp in file_paths:
            img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
            image_data.append(img)
            image_listbox.insert(tk.END, fp)

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []

    # Генерация блоков, пока размеры позволяют
    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))  # Ограничиваем максимальный размер блока
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        # Прерываем цикл, если достигли ограничения на количество блоков для оптимизации
        if len(blocks) >= 50:  # Лимит на 50 блоков для предотвращения зависания
            break

    return blocks

def generate_random_mosaic(images):
    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    for img in images:
        blocks = split_image(img)
        for block in blocks:
            block_height, block_width, _ = block.shape
            
            # Генерируем случайные позиции на холсте для наложения
            x = random.randint(0, canvas_width - block_width)
            y = random.randint(0, canvas_height - block_height)

            # Накладываем блок на холст
            flat_mosaic[y:y + block_height, x:x + block_width] = block

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas
    if canvas is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x500")

load_image_button = tk.Button(root, text="Загрузить изображения", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

root.mainloop()

Код гитхаб.

Последний раз редактировалось MakarovDs; 09.02.2025 в 23:04.
MakarovDs на форуме Ответить с цитированием
Старый 10.02.2025, 00:24   #53
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Хотел сделать без стыков но получилась типа пустота между кадрами ну все равно может кому понадобиться? Все равно никто такое не делал до меня я первый на этой планете...
Код:
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
import random
import os

# Параметры
image_data = []
canvas = None
current_flat_mosaic = None
canvas_width = 640
canvas_height = 480
update_interval = 100
is_running = False

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_paths:
        for fp in file_paths:
            img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
            image_data.append(img)
            image_listbox.insert(tk.END, fp)

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []

    # Генерация блоков, пока размеры позволяют
    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.full((canvas_height, canvas_width, 3), (255, 255, 255), dtype=np.uint8)  # Белый фон

    # Список всех блоков для формирования мозаики
    total_blocks = []
    for img in images:
        blocks = split_image(img)
        total_blocks.extend(blocks)

    # Перемешиваем блоки для случайных добавлений
    random.shuffle(total_blocks)

    # Заполнение мозаики
    for block in total_blocks:
        block_height, block_width, _ = block.shape
        
        # Поиск первого доступного места на холсте, чтобы установить блок
        placed = False
        for _ in range(100):  # Попыток разместить блок
            x = random.randint(0, canvas_width - block_width)
            y = random.randint(0, canvas_height - block_height)

            # Накладываем блок на холст, перезаписывая
            if np.all(flat_mosaic[y:y + block_height, x:x + block_width] == (255, 255, 255)):
                flat_mosaic[y:y + block_height, x:x + block_width] = block
                placed = True
                break

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas
    if canvas is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x500")

load_image_button = tk.Button(root, text="Загрузить изображения", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

root.mainloop()

Гитхаб код.

Последний раз редактировалось MakarovDs; 10.02.2025 в 00:31.
MakarovDs на форуме Ответить с цитированием
Старый 10.02.2025, 01:12   #54
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Хотел сделать без пустоты заднего фона но это самое лучшие что получилось:
Код:
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
import random
import os

# Параметры
image_data = []
canvas = None
current_flat_mosaic = None
canvas_width = 640
canvas_height = 480
update_interval = 100
is_running = False

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_paths:
        for fp in file_paths:
            img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
            image_data.append(img)
            image_listbox.insert(tk.END, fp)

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []

    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)  # Черный фон

    # Генерация случайных блоков для фона
    for _ in range(10):  # Установите количество слоев фона
        img = random.choice(images)
        blocks = split_image(img)
        for block in blocks:
            block_height, block_width, _ = block.shape
            
            # Поиск места для размещения блока
            x = random.randint(0, canvas_width - block_width)
            y = random.randint(0, canvas_height - block_height)

            # Размещение блока
            flat_mosaic[y:y + block_height, x:x + block_width] = block

    total_blocks = []
    for img in images:
        blocks = split_image(img)
        total_blocks.extend(blocks)

    current_x = 0
    current_y = 0
    
    for block in total_blocks:
        block_height, block_width, _ = block.shape
        
        if current_y + block_height > canvas_height:
            break

        if current_x + block_width > canvas_width:
            current_x = 0
            current_y += block_height
            if current_y + block_height > canvas_height:
                break

        # Наложение блока на готовую мозаику
        flat_mosaic[current_y:current_y + block_height, current_x:current_x + block_width] = block
        
        current_x += block_width  # Переход на следующую позицию по горизонтали

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas
    if canvas is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x500")

load_image_button = tk.Button(root, text="Загрузить изображения", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

root.mainloop()
как всегда ссылка.

Последний раз редактировалось MakarovDs; 10.02.2025 в 01:14.
MakarovDs на форуме Ответить с цитированием
Старый 11.02.2025, 00:05   #55
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Теперь нужно добавить возможно добавлять видео
Код:
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
import random
import os
import cv2  # Импортируем OpenCV

# Параметры
image_data = []
canvas = None
current_flat_mosaic = None
canvas_width = 640
canvas_height = 480
update_interval = 100
is_running = False

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.mp4;*.avi")])
    if file_paths:
        for fp in file_paths:
            if fp.endswith(('.jpg', '.png', '.jpeg')):
                img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
                image_data.append(img)
                image_listbox.insert(tk.END, fp)  # Добавляем изображение в Listbox
            elif fp.endswith(('.mp4', '.avi')):
                # Извлечение случайных кадров из видео
                video_frames = extract_random_frames(fp)
                image_data.extend(video_frames)
                image_listbox.insert(tk.END, fp)  # Добавляем видео в Listbox

def extract_random_frames(video_path, num_frames=10):
    frames = []
    cap = cv2.VideoCapture(video_path)

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frame_indices = random.sample(range(total_frames), min(num_frames, total_frames))  # Случайные индексы кадров

    for idx in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, idx)  # Установка на индекс кадра
        ret, frame = cap.read()
        if ret:
            frame = cv2.resize(frame, (canvas_width, canvas_height))  # Изменение размера кадра
            frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))  # Конвертация цвета
    cap.release()
    return frames

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []

    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_y + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic_background = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)  # Задний фон
    flat_mosaic_foreground = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)  # Передний план

    # Генерация случайных блоков для заднего фона
    for _ in range(10):  # Установите количество слоев фона
        img = random.choice(images)
        blocks = split_image(img)
        for block in blocks:
            block_height, block_width, _ = block.shape
            
            # Поиск места для размещения блока на заднем фоне
            x = random.randint(0, canvas_width - block_width)
            y = random.randint(0, canvas_height - block_height)

            # Размещение блока на заднем фоне
            flat_mosaic_background[y:y + block_height, x:x + block_width] = block

    # Генерация случайных блоков для переднего плана
    for img in images:
        blocks = split_image(img)
        for block in blocks:
            block_height, block_width, _ = block.shape
            
            # Поиск места для размещения блока на переднем плане
            x = random.randint(0, canvas_width - block_width)
            y = random.randint(0, canvas_height - block_height)

            # Наложение блока на передний план
            flat_mosaic_foreground[y:y + block_height, x:x + block_width] = block

    # Смешиваем задний план и передний план
    flat_mosaic_combined = np.maximum(flat_mosaic_background, flat_mosaic_foreground)

    return flat_mosaic_combined

def update_canvas(flat_mosaic):
    global canvas
    if canvas is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x500")

load_image_button = tk.Button(root, text="Загрузить изображения/видео", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

root.mainloop()

Код ГИТХАБ
MakarovDs на форуме Ответить с цитированием
Старый 11.02.2025, 00:11   #56
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Но можно сделать и в один слой, вот однослойная версия:
Код:
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog
import random
import os
import cv2  # Импортируем OpenCV

# Параметры
image_data = []
canvas = None
current_flat_mosaic = None
canvas_width = 640
canvas_height = 480
update_interval = 100
is_running = False

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.mp4;*.avi")])
    if file_paths:
        for fp in file_paths:
            if fp.endswith(('.jpg', '.png', '.jpeg')):
                img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
                image_data.append(img)
                image_listbox.insert(tk.END, fp)  # Добавляем изображение в Listbox
            elif fp.endswith(('.mp4', '.avi')):
                # Извлечение случайных кадров из видео
                video_frames = extract_random_frames(fp)
                image_data.extend(video_frames)
                image_listbox.insert(tk.END, fp)  # Добавляем видео в Listbox

def extract_random_frames(video_path, num_frames=10):
    frames = []
    cap = cv2.VideoCapture(video_path)

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frame_indices = random.sample(range(total_frames), min(num_frames, total_frames))  # Случайные индексы кадров

    for idx in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, idx)  # Установка на индекс кадра
        ret, frame = cap.read()
        if ret:
            frame = cv2.resize(frame, (canvas_width, canvas_height))  # Изменение размера кадра
            frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))  # Конвертация цвета
    cap.release()
    return frames

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []

    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)  # Черный фон

    # Генерация случайных блоков для фона
    for _ in range(10):  # Установите количество слоев фона
        img = random.choice(images)
        blocks = split_image(img)
        for block in blocks:
            block_height, block_width, _ = block.shape
            
            # Поиск места для размещения блока
            x = random.randint(0, canvas_width - block_width)
            y = random.randint(0, canvas_height - block_height)

            # Размещение блока
            flat_mosaic[y:y + block_height, x:x + block_width] = block

    total_blocks = []
    for img in images:
        blocks = split_image(img)
        total_blocks.extend(blocks)

    current_x = 0
    current_y = 0
    
    for block in total_blocks:
        block_height, block_width, _ = block.shape
        
        if current_y + block_height > canvas_height:
            break

        if current_x + block_width > canvas_width:
            current_x = 0
            current_y += block_height
            if current_y + block_height > canvas_height:
                break

        # Наложение блока на готовую мозаику
        flat_mosaic[current_y:current_y + block_height, current_x:current_x + block_width] = block
        
        current_x += block_width  # Переход на следующую позицию по горизонтали

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas
    if canvas is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x500")

load_image_button = tk.Button(root, text="Загрузить изображения/видео", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

root.mainloop()
Гитхаб код

Последний раз редактировалось MakarovDs; 11.02.2025 в 00:16.
MakarovDs на форуме Ответить с цитированием
Старый 11.02.2025, 00:18   #57
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

В БАССЕЙНЕ ПОЛНОМ РАЗБИТОГО СТЕКЛАЛАЛАЛАЛАААААААА

СТАВЛЮ РЕКОРДЫ НА СКОРОСТЬ И ГЛУБИНУНУНУНУНАНАНАААААААА


Последний раз редактировалось MakarovDs; 11.02.2025 в 00:35.
MakarovDs на форуме Ответить с цитированием
Старый 13.02.2025, 23:57   #58
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Отлично теперь мы можем заменить цветной шум на бесконечную карту мозаик.
Код:
import tkinter as tk
from tkinter import filedialog
import numpy as np
from PIL import Image, ImageTk
import random
import os

# Параметры холста
canvas_width = 640
canvas_height = 480
image_data = []
current_flat_mosaic = None
update_interval = 100
is_running = False
canvas = None  # Инициализация переменной canvas
canvas_window = None  # Инициализация переменной canvas_window

# Параметры координат
x, y, z = 0, 0, 0
used_blocks = []  # Хранит уже использованные блоки для избежания повторений
mosaic_storage = {}  # Сохраняет мозаики по координатам

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_paths:
        image_data.clear()  # Очистить предыдущие изображения
        for fp in file_paths:
            img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
            image_data.append(img)
            image_listbox.insert(tk.END, fp)

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []
    
    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    global used_blocks
    used_blocks = []  # Сброс используемых блоков перед новой генерацией

    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    while len(used_blocks) < len(images) * 50:  # Ограничивающий фактор
        img = random.choice(images)
        blocks = split_image(img)

        for block in blocks:
            if block.tobytes() not in used_blocks:
                used_blocks.append(block.tobytes())
                block_height, block_width, _ = block.shape

                # Находим случайные координаты
                x_pos = random.randint(0, canvas_width - block_width)
                y_pos = random.randint(0, canvas_height - block_height)

                flat_mosaic[y_pos:y_pos + block_height, x_pos:x_pos + block_width] = block

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas, canvas_window
    if canvas_window is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

    # Добавляем табло с порезанными кадрами
    image_frame = tk.Frame(canvas_window)
    image_frame.pack()

    for image in image_data:
        image_pil = Image.fromarray(np.uint8(image))
        image_tk = ImageTk.PhotoImage(image_pil)
        image_label = tk.Label(image_frame, image=image_pil)
        image_label.image = image_pil
        image_label.pack(side=tk.LEFT)

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        # Сохраняем мозаику по текущей координате
        mosaic_storage[(x, y)] = current_flat_mosaic
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

def move_left():
    global x
    x -= 1
    update_mosaic()

def move_right():
    global x
    x += 1
    update_mosaic()

def move_up():
    global y
    y += 1
    update_mosaic()

def move_down():
    global y
    y -= 1
    update_mosaic()

def update_mosaic():
    global current_flat_mosaic

    # Проверяем, существует ли мозайка для текущих координат
    if (x, y) in mosaic_storage:
        current_flat_mosaic = mosaic_storage[(x, y)]  # Используем сохранённую мозаику
    else:
        current_flat_mosaic = generate_random_mosaic(image_data)  # Генерируем новую, если нет сохраненной
        mosaic_storage[(x, y)] = current_flat_mosaic  # Сохраняем новую мозаику

    update_canvas(current_flat_mosaic)
    update_coordinates_display()  # Обновляем табло координат после обновления мозаики

def update_coordinates_display():
    coordinates_label.config(text=f"Координаты - x: {x}, y: {y}, z: {z}")

# Основной интерфейс
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x700")

# Табло для координат
coordinates_label = tk.Label(root, text=f"Координаты - x: {x}, y: {y}, z: {z}")
coordinates_label.pack()

# Кнопки загрузки и управления
load_image_button = tk.Button(root, text="Загрузить изображения", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

# Кнопки перемещения
move_buttons_frame = tk.Frame(root)
move_buttons_frame.pack()

left_button = tk.Button(move_buttons_frame, text="Влево", command=move_left)
left_button.grid(row=0, column=0)

right_button = tk.Button(move_buttons_frame, text="Вправо", command=move_right)
right_button.grid(row=0, column=2)

up_button = tk.Button(move_buttons_frame, text="Вверх", command=move_up)
up_button.grid(row=1, column=1)

down_button = tk.Button(move_buttons_frame, text="Вниз", command=move_down)
down_button.grid(row=2, column=1)

root.mainloop()
Код гитхаб -> ссылка.

Последний раз редактировалось MakarovDs; 14.02.2025 в 00:13.
MakarovDs на форуме Ответить с цитированием
Старый 14.02.2025, 22:48   #59
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Гитхаб.
Код:
import tkinter as tk
from tkinter import filedialog
import numpy as np
from PIL import Image, ImageTk
import random
import os
import threading
import time

canvas_width = 640
canvas_height = 480
image_data = []
current_flat_mosaic = None
update_interval = 100
is_running = False
canvas = None 
canvas_window = None

x, y, z = 0, 0, 0
seed = 42
auto_random_running = False
auto_random_thread = None
auto_random_delay = 1
used_blocks = []
mosaic_storage = {}

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg")])
    if file_paths:
        for fp in file_paths:
            img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
            image_data.append(img)
            image_listbox.insert(tk.END, os.path.basename(fp))

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []
    
    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    global used_blocks
    used_blocks = []

    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    while len(used_blocks) < len(images) * 50:
        img = random.choice(images)
        blocks = split_image(img)

        for block in blocks:
            if block.tobytes() not in used_blocks:
                used_blocks.append(block.tobytes())
                block_height, block_width, _ = block.shape

                x_pos = random.randint(0, canvas_width - block_width)
                y_pos = random.randint(0, canvas_height - block_height)

                flat_mosaic[y_pos:y_pos + block_height, x_pos:x_pos + block_width] = block

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas, canvas_window
    if canvas_window is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        mosaic_storage[(x, y)] = current_flat_mosaic
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

def move_left():
    global x
    x -= 1
    update_mosaic()

def move_right():
    global x
    x += 1
    update_mosaic()

def move_up():
    global y
    y += 1
    update_mosaic()

def move_down():
    global y
    y -= 1
    update_mosaic()

def update_mosaic():
    global current_flat_mosaic

    if (x, y) in mosaic_storage:
        current_flat_mosaic = mosaic_storage[(x, y)]
    else:
        current_flat_mosaic = generate_random_mosaic(image_data)
        mosaic_storage[(x, y)] = current_flat_mosaic

    update_canvas(current_flat_mosaic)
    update_coordinates_display()

def update_coordinates_display():
    coordinates_label.config(text=f"Координаты - x: {x}, y: {y}, z: {z}, Seed: {seed}")

def toggle_auto_random():
    global auto_random_running, auto_random_thread
    if auto_random_running:
        auto_random_running = False
        if auto_random_thread is not None:
            auto_random_thread.join() 
        auto_random_button.config(text="Запустить авторандом")
    else:
        auto_random_running = True
        auto_random_button.config(text="Остановить авторандом")
        auto_random_thread = threading.Thread(target=auto_random_coordinates)
        auto_random_thread.start()

def auto_random_coordinates():
    global x, y, z, auto_random_delay
    while auto_random_running:
        x = random.randint(0, 10000)
        y = random.randint(0, 10000)
        z = random.randint(0, 10000)
        update_mosaic()
        update_coordinates_display()
        time.sleep(auto_random_delay) 

def set_seed():
    global seed
    try:
        seed = int(seed_entry.get())
        update_coordinates_display()
    except ValueError:
        seed_entry.delete(0, tk.END)
        seed_entry.insert(0, str(seed))

def set_auto_random_delay():
    global auto_random_delay
    try:
        delay = float(auto_random_delay_entry.get())
        if delay > 0:
            auto_random_delay = delay
    except ValueError:
        auto_random_delay_entry.delete(0, tk.END)
        auto_random_delay_entry.insert(0, str(auto_random_delay))

root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x700")

coordinates_label = tk.Label(root, text=f"Координаты - x: {x}, y: {y}, z: {z}, Seed: {seed}")
coordinates_label.pack()

load_image_button = tk.Button(root, text="Загрузить изображения", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

seed_label = tk.Label(root, text="Сид:")
seed_label.pack()

seed_entry = tk.Entry(root)
seed_entry.pack()
seed_entry.insert(0, str(seed))

set_seed_button = tk.Button(root, text="Установить сид", command=set_seed)
set_seed_button.pack()

auto_random_button = tk.Button(root, text="Запустить авторандом", command=toggle_auto_random)
auto_random_button.pack()

auto_random_delay_label = tk.Label(root, text="Скорость авторандома (сек):")
auto_random_delay_label.pack()

auto_random_delay_entry = tk.Entry(root)
auto_random_delay_entry.pack()
auto_random_delay_entry.insert(0, str(auto_random_delay))

set_auto_random_delay_button = tk.Button(root, text="Установить задержку", command=set_auto_random_delay)
set_auto_random_delay_button.pack()

image_listbox = tk.Listbox(root, width=60, height=15)
image_listbox.pack()

move_buttons_frame = tk.Frame(root)
move_buttons_frame.pack()

left_button = tk.Button(move_buttons_frame, text="Влево", command=move_left)
left_button.grid(row=0, column=0)

right_button = tk.Button(move_buttons_frame, text="Вправо", command=move_right)
right_button.grid(row=0, column=2)

up_button = tk.Button(move_buttons_frame, text="Вверх", command=move_up)
up_button.grid(row=1, column=1)

down_button = tk.Button(move_buttons_frame, text="Вниз", command=move_down)
down_button.grid(row=2, column=1)

root.mainloop()

Последний раз редактировалось MakarovDs; 14.02.2025 в 22:51.
MakarovDs на форуме Ответить с цитированием
Старый Вчера, 17:45   #60
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 350
По умолчанию

Забыл добавить что-бы можно было не только картинки но и видео загружать, теперь новая третья версия кода.

Код:
...

def load_images():
    global image_data
    file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.mp4;*.avi")])
    if file_paths:
        for fp in file_paths:
            if fp.endswith(('.jpg', '.png', '.jpeg')):
                img = np.array(Image.open(fp).resize((canvas_width, canvas_height)).convert("RGB"))
                image_data.append(img)
                image_listbox.insert(tk.END, os.path.basename(fp))  # Добавляем изображение в Listbox
            elif fp.endswith(('.mp4', '.avi')):
                # Извлечение случайных кадров из видео
                video_frames = extract_random_frames(fp)
                image_data.extend(video_frames)
                image_listbox.insert(tk.END, os.path.basename(fp))  # Добавляем видео в Listbox

def extract_random_frames(video_path, num_frames=10):
    frames = []
    cap = cv2.VideoCapture(video_path)

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frame_indices = random.sample(range(total_frames), min(num_frames, total_frames))  # Случайные индексы кадров

    for idx in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, idx)  # Установка на индекс кадра
        ret, frame = cap.read()
        if ret:
            frame = cv2.resize(frame, (canvas_width, canvas_height))  # Изменение размера кадра
            frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))  # Конвертация цвета до RGB
    cap.release()
    return frames

def split_image(image, min_size=20):
    height, width, _ = image.shape
    blocks = []
    
    while height >= min_size and width >= min_size:
        block_width = random.randint(min_size, min(width, 100))
        block_height = random.randint(min_size, min(height, 100))

        start_x = random.randint(0, width - block_width)
        start_y = random.randint(0, height - block_height)

        block = image[start_y:start_y + block_height, start_x:start_x + block_width]
        blocks.append(block)

        if len(blocks) >= 50:
            break

    return blocks

def generate_random_mosaic(images):
    global used_blocks
    used_blocks = []

    if len(images) == 0:
        return np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    flat_mosaic = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

    while len(used_blocks) < len(images) * 50:
        img = random.choice(images)
        blocks = split_image(img)

        for block in blocks:
            if block.tobytes() not in used_blocks:
                used_blocks.append(block.tobytes())
                block_height, block_width, _ = block.shape

                x_pos = random.randint(0, canvas_width - block_width)
                y_pos = random.randint(0, canvas_height - block_height)

                flat_mosaic[y_pos:y_pos + block_height, x_pos:x_pos + block_width] = block

    return flat_mosaic

def update_canvas(flat_mosaic):
    global canvas, canvas_window
    if canvas_window is None:
        canvas_window = tk.Toplevel()
        canvas = tk.Canvas(canvas_window, width=canvas_width, height=canvas_height)
        canvas.pack()

    mosaic_image = Image.fromarray(np.uint8(flat_mosaic))
    mosaic_image_tk = ImageTk.PhotoImage(mosaic_image)
    canvas.delete('all')
    canvas.create_image(0, 0, anchor=tk.NW, image=mosaic_image_tk)
    canvas.image = mosaic_image_tk

def start_mosaic():
    global is_running
    if image_data and not is_running:
        is_running = True
        run_mosaic_animation()

def run_mosaic_animation():
    global current_flat_mosaic, is_running
    if is_running:
        current_flat_mosaic = generate_random_mosaic(image_data)
        mosaic_storage[(x, y)] = current_flat_mosaic
        update_canvas(current_flat_mosaic)
        root.after(update_interval, run_mosaic_animation)

def stop_mosaic():
    global is_running
    is_running = False

def save_image():
    global current_flat_mosaic
    if current_flat_mosaic is not None and current_flat_mosaic.size > 0:
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        save_path = os.path.join(desktop_path, "mosaic_image.png")
        mosaic_image = Image.fromarray(np.uint8(current_flat_mosaic))
        mosaic_image.save(save_path)
        print(f"Изображение сохранено по: {save_path}")

def move_left():
    global x
    x -= 1
    update_mosaic()

def move_right():
    global x
    x += 1
    update_mosaic()

def move_up():
    global y
    y += 1
    update_mosaic()

def move_down():
    global y
    y -= 1
    update_mosaic()

def update_mosaic():
    global current_flat_mosaic

    if (x, y) in mosaic_storage:
        current_flat_mosaic = mosaic_storage[(x, y)]
    else:
        current_flat_mosaic = generate_random_mosaic(image_data)
        mosaic_storage[(x, y)] = current_flat_mosaic

    update_canvas(current_flat_mosaic)
    update_coordinates_display()

def update_coordinates_display():
    coordinates_label.config(text=f"Координаты - x: {x}, y: {y}, z: {z}, Seed: {seed}")

def toggle_auto_random():
    global auto_random_running, auto_random_thread
    if auto_random_running:
        auto_random_running = False
        if auto_random_thread is not None:
            auto_random_thread.join() 
        auto_random_button.config(text="Запустить авторандом")
    else:
        auto_random_running = True
        auto_random_button.config(text="Остановить авторандом")
        auto_random_thread = threading.Thread(target=auto_random_coordinates)
        auto_random_thread.start()

def auto_random_coordinates():
    global x, y, z, auto_random_delay
    while auto_random_running:
        x = random.randint(0, 10000)
        y = random.randint(0, 10000)
        z = random.randint(0, 10000)
        update_mosaic()
        update_coordinates_display()
        time.sleep(auto_random_delay) 

def set_seed():
    global seed
    try:
        seed = int(seed_entry.get())
        update_coordinates_display()
    except ValueError:
        seed_entry.delete(0, tk.END)
        seed_entry.insert(0, str(seed))

def set_auto_random_delay():
    global auto_random_delay
    try:
        delay = float(auto_random_delay_entry.get())
        if delay > 0:
            auto_random_delay = delay
    except ValueError:
        auto_random_delay_entry.delete(0, tk.END)
        auto_random_delay_entry.insert(0, str(auto_random_delay))

# Создание основного окна
root = tk.Tk()
root.title("Генератор мозаики")
root.geometry("400x700")

coordinates_label = tk.Label(root, text=f"Координаты - x: {x}, y: {y}, z: {z}, Seed: {seed}")
coordinates_label.pack()

load_image_button = tk.Button(root, text="Загрузить изображения/видео", command=load_images)
load_image_button.pack()

start_button = tk.Button(root, text="Запустить мозаику", command=start_mosaic)
start_button.pack()

stop_button = tk.Button(root, text="Остановить мозаику", command=stop_mosaic)
stop_button.pack()

save_image_button = tk.Button(root, text="Сохранить мозаику", command=save_image)
save_image_button.pack()

seed_label = tk.Label(root, text="Сид:")
seed_label.pack()

seed_entry = tk.Entry(root)
seed_entry.pack()
seed_entry.insert(0, str(seed))

...


Ссылка на гитхаб -> ссылка.

Последний раз редактировалось MakarovDs; Вчера в 17:48.
MakarovDs на форуме Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Реализация симуляции банкомата A7A7A7 Общие вопросы C/C++ 0 15.09.2023 23:48
Технологии симуляции жизни в играх Человек_Борща Свободное общение 6 22.11.2013 14:59
Создание большого 3D мира ardor Gamedev - cоздание игр: Unity, OpenGL, DirectX 4 02.03.2012 00:14
Создание катры мира (от Яндекса) с помощью Дельфи Alex Cones Общие вопросы Delphi 2 27.05.2009 09:16
Компьютерное моделирование. Создание модели движения тел по определенной траектории. AnaVare Помощь студентам 7 18.03.2009 05:09