|
import gradio as gr |
|
import numpy as np |
|
from PIL import Image |
|
import random |
|
import tempfile |
|
import os |
|
from zipfile import ZipFile |
|
|
|
def apply_random_transformations(image): |
|
|
|
transformations = [rotate_image, zoom_image, add_noise] |
|
random.shuffle(transformations) |
|
|
|
for transform in transformations: |
|
if random.choice([True, False]): |
|
image = transform(image) |
|
return image |
|
|
|
def rotate_image(image): |
|
angle = random.randint(-30, 30) |
|
return image.rotate(angle) |
|
|
|
def zoom_image(image): |
|
zoom_factor = random.uniform(0.9, 1.1) |
|
width, height = image.size |
|
new_width = int(width * zoom_factor) |
|
new_height = int(height * zoom_factor) |
|
return image.resize((new_width, new_height), Image.LANCZOS) |
|
|
|
def add_noise(image_np): |
|
noise = np.random.randn(*image_np.shape) * 25 |
|
noisy_image = np.clip(image_np + noise, 0, 255) |
|
return Image.fromarray(noisy_image.astype(np.uint8)) |
|
|
|
def sepia(input_img, num_copies): |
|
sepia_filter = np.array([ |
|
[0.393, 0.769, 0.189], |
|
[0.349, 0.686, 0.168], |
|
[0.272, 0.534, 0.131] |
|
]) |
|
input_img = np.array(input_img) / 255.0 |
|
sepia_imgs = [] |
|
for _ in range(num_copies): |
|
|
|
sepia_img = np.dot(input_img[..., :3], sepia_filter.T) |
|
sepia_img = np.clip(sepia_img, 0, 1) * 255 |
|
img_pil = Image.fromarray(sepia_img.astype(np.uint8)) |
|
|
|
|
|
img_transformed = apply_random_transformations(img_pil) |
|
sepia_imgs.append(img_transformed) |
|
|
|
return sepia_imgs |
|
|
|
def zip_sepia_images(sepia_imgs): |
|
temp_dir = tempfile.mkdtemp() |
|
zip_path = os.path.join(temp_dir, "sepia_images.zip") |
|
with ZipFile(zip_path, 'w') as zipf: |
|
for i, img in enumerate(sepia_imgs): |
|
img_path = os.path.join(temp_dir, f"sepia_image_{i}.png") |
|
img.save(img_path) |
|
zipf.write(img_path, os.path.basename(img_path)) |
|
shutil.rmtree(temp_dir) |
|
return zip_path |
|
|
|
with gr.Blocks() as demo: |
|
with gr.Row(): |
|
input_img = gr.Image(tool="editor") |
|
num_copies = gr.Number(label="Number of Copies", value=1) |
|
gallery = gr.Gallery(label="Sepia Images") |
|
download_btn = gr.File(label="Download ZIP") |
|
|
|
generate_btn = gr.Button("Generate Sepia Images") |
|
generate_btn.click(fn=sepia, inputs=[input_img, num_copies], outputs=gallery) |
|
generate_btn.click(fn=zip_sepia_images, inputs=gallery, outputs=download_btn) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|