|
import gradio as gr |
|
from tensorflow.keras.preprocessing.image import img_to_array, ImageDataGenerator |
|
from PIL import Image |
|
import os |
|
import zipfile |
|
|
|
|
|
TEMP_DIR = "temp_augmented_images" |
|
|
|
|
|
if not os.path.exists(TEMP_DIR): |
|
os.makedirs(TEMP_DIR) |
|
|
|
|
|
def augment_image(image_file, datagen, num_duplicates): |
|
try: |
|
img = Image.open(image_file).convert('RGB') |
|
img = img.resize((256, 256)) |
|
x = img_to_array(img) |
|
x = x.reshape((1,) + x.shape) |
|
|
|
|
|
i = 0 |
|
for batch in datagen.flow(x, batch_size=1, save_to_dir=TEMP_DIR, save_prefix="aug", save_format="jpeg"): |
|
i += 1 |
|
if i >= num_duplicates: |
|
break |
|
except Exception as e: |
|
print(f"Error in augmenting image: {e}") |
|
|
|
def create_zip_from_temp(directory=TEMP_DIR): |
|
zip_path = f"{directory}/augmented_images.zip" |
|
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: |
|
for root, _, files in os.walk(directory): |
|
for file in files: |
|
if file.endswith(".jpeg"): |
|
zipf.write(os.path.join(root, file), arcname=file) |
|
return zip_path |
|
|
|
def process_images(images, num_duplicates): |
|
|
|
datagen = ImageDataGenerator( |
|
rotation_range=40, |
|
width_shift_range=0.2, |
|
height_shift_range=0.2, |
|
zoom_range=0.2, |
|
fill_mode='nearest') |
|
|
|
|
|
for image_file in images: |
|
augment_image(image_file, datagen, num_duplicates) |
|
|
|
|
|
zip_file = create_zip_from_temp() |
|
|
|
|
|
for file in os.listdir(TEMP_DIR): |
|
if file.endswith(".jpeg"): |
|
os.remove(os.path.join(TEMP_DIR, file)) |
|
|
|
return zip_file |
|
|
|
|
|
demo = gr.Interface( |
|
fn=process_images, |
|
inputs=[ |
|
gr.Files(type="file", label="Upload Images", accept=["image/jpeg", "image/png"], multiple=True), |
|
gr.Slider(minimum=1, maximum=20, default=5, label="Number of Duplicates per Image") |
|
], |
|
outputs=gr.File(label="Download Augmented Images"), |
|
title="Image Augmentation App", |
|
description="Upload images to augment them with random transformations. Download the augmented images as a zip file." |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|