LPX55's picture
Update app.py
1eb15ec verified
raw
history blame
1.72 kB
import gradio as gr
import numpy as np
import zipfile
import io
from PIL import Image
def split_image_grid(image, grid_size):
# Convert the image to a NumPy array
img = np.array(image)
width, height = img.shape[1], img.shape[0]
grid_width, grid_height = grid_size, grid_size
# Calculate the size of each grid cell
cell_width = width // grid_width
cell_height = height // grid_height
# Split the image into individual frames
frames = []
for i in range(grid_height):
for j in range(grid_width):
left = j * cell_width
upper = i * cell_height
right = (j + 1) * cell_width
lower = (i + 1) * cell_height
frame = img[upper:lower, left:right]
frames.append(frame)
return frames
def create_zip_file(frames):
# Create an in-memory zip file
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zipf:
for idx, frame in enumerate(frames):
frame_byte_array = io.BytesIO()
# Save the frame as a PNG file in the byte array
frame_img = Image.fromarray(frame)
frame_img.save(frame_byte_array, format="PNG")
zipf.writestr(f"frame_{idx}.png", frame_byte_array.getvalue())
zip_buffer.seek(0)
return zip_buffer
def create_gif(frames):
# Create a GIF from the frames
gif_buffer = io.BytesIO()
frames_pil = [Image.fromarray(frame) for frame in frames]
frames_pil[0].save(gif_buffer, format="GIF", save_all=True, append_images=frames_pil[1:], loop=0)
gif_buffer.seek(0) # Ensure the buffer is at the beginning
return gif_buffer
def process_image(image, grid_size):
frames = split_image