|
import gradio as gr |
|
import numpy as np |
|
import zipfile |
|
from io import BytesIO |
|
|
|
def split_image_grid(image, grid_size): |
|
|
|
img = np.array(image) |
|
width, height = img.shape[1], img.shape[0] |
|
grid_width, grid_height = grid_size |
|
|
|
|
|
cell_width = width // grid_width |
|
cell_height = height // grid_height |
|
|
|
|
|
frames = [] |
|
for i in range(grid_height): |
|
for j in range(grid_width): |
|
left = j * cell_width |
|
upper = i * cell_height |
|
right = left + cell_width |
|
lower = upper + cell_height |
|
frame = img[upper:lower, left:right] |
|
frames.append(frame) |
|
|
|
return frames |
|
|
|
def zip_images(images): |
|
|
|
zip_buffer = BytesIO() |
|
with zipfile.ZipFile(zip_buffer, 'w') as zipf: |
|
for idx, img in enumerate(images): |
|
|
|
img_buffer = BytesIO() |
|
img = Image.fromarray(img) |
|
img.save(img_buffer, format='PNG') |
|
img_buffer.seek(0) |
|
zipf.writestr(f'image_{idx}.png', img_buffer.getvalue()) |
|
|
|
zip_buffer.seek(0) |
|
return zip_buffer |
|
|
|
with gr.Blocks() as demo: |
|
with gr.Row(): |
|
image_input = gr.Image(label="Input Image") |
|
grid_size_input = gr.Slider(1, 10, value=2, step=1, label="Grid Size") |
|
split_button = gr.Button("Split Image") |
|
zip_output = gr.File(label="Download Zipped Images") |
|
|
|
def process_image(image, grid_size): |
|
|
|
frames = split_image_grid(image, (grid_size, grid_size)) |
|
|
|
zip_file = zip_images(frames) |
|
return zip_file |
|
|
|
split_button.click(process_image, inputs=[image_input, grid_size_input], outputs=zip_output) |
|
|
|
demo.launch(show_error=True) |