Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,58 @@
|
|
1 |
-
import numpy as np
|
2 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
13 |
|
14 |
-
|
15 |
-
demo.launch()
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from tensorflow.keras.preprocessing.image import img_to_array, ImageDataGenerator
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
import io
|
6 |
+
import zipfile
|
7 |
+
|
8 |
+
def augment_images(images, num_duplicates):
|
9 |
+
# Initialize the image data generator for augmentation
|
10 |
+
datagen = ImageDataGenerator(
|
11 |
+
rotation_range=40,
|
12 |
+
width_shift_range=0.2,
|
13 |
+
height_shift_range=0.2,
|
14 |
+
zoom_range=0.2,
|
15 |
+
fill_mode='nearest')
|
16 |
+
|
17 |
+
# Create a zip buffer in memory
|
18 |
+
zip_buffer = io.BytesIO()
|
19 |
+
|
20 |
+
with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zipf:
|
21 |
+
for i, img_file in enumerate(images):
|
22 |
+
# Open image and prepare for augmentation
|
23 |
+
img = Image.open(img_file).convert('RGB')
|
24 |
+
img = img.resize((256, 256)) # Resize for consistency
|
25 |
+
x = img_to_array(img) # Convert to array
|
26 |
+
x = np.expand_dims(x, axis=0) # Add batch dimension
|
27 |
+
|
28 |
+
# Generate augmented images and add them to the zip
|
29 |
+
for j in range(num_duplicates):
|
30 |
+
aug_iter = datagen.flow(x, batch_size=1)
|
31 |
+
aug_image = next(aug_iter)[0].astype('uint8')
|
32 |
+
aug_image_pil = Image.fromarray(aug_image)
|
33 |
+
|
34 |
+
# Save augmented image to zip
|
35 |
+
img_byte_arr = io.BytesIO()
|
36 |
+
aug_image_pil.save(img_byte_arr, format='PNG')
|
37 |
+
img_byte_arr = img_byte_arr.getvalue()
|
38 |
+
zipf.writestr(f"augmented_image_{i}_{j}.png", img_byte_arr)
|
39 |
+
|
40 |
+
# Prepare the zip file for downloading
|
41 |
+
zip_buffer.seek(0)
|
42 |
+
|
43 |
+
return zip_buffer
|
44 |
|
45 |
+
# Define Gradio interface
|
46 |
+
demo = gr.Interface(
|
47 |
+
fn=augment_images,
|
48 |
+
inputs=[
|
49 |
+
gr.Files(label="Upload Images", multiple=True),
|
50 |
+
gr.Slider(minimum=1, maximum=10, default=5, label="Number of Augmented Images per Original")
|
51 |
+
],
|
52 |
+
outputs=gr.File(label="Download Augmented Images Zip"),
|
53 |
+
title="Image Augmentation App",
|
54 |
+
description="Upload images to generate augmented versions. Adjust the number of augmented images per original image using the slider."
|
55 |
+
)
|
56 |
|
57 |
+
if __name__ == "__main__":
|
58 |
+
demo.launch()
|