Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
datagen = ImageDataGenerator(
|
10 |
+
rotation_range=40,
|
11 |
+
width_shift_range=0.2,
|
12 |
+
height_shift_range=0.2,
|
13 |
+
zoom_range=0.2,
|
14 |
+
fill_mode='nearest')
|
15 |
+
|
16 |
+
# Initialize in-memory zip file
|
17 |
+
zip_buffer = io.BytesIO()
|
18 |
+
|
19 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
20 |
+
for i, img_file in enumerate(images):
|
21 |
+
img = Image.open(img_file).convert('RGB')
|
22 |
+
img = img.resize((256, 256))
|
23 |
+
x = img_to_array(img)
|
24 |
+
x = np.expand_dims(x, axis=0)
|
25 |
+
|
26 |
+
for j in range(num_duplicates):
|
27 |
+
it = datagen.flow(x, batch_size=1)
|
28 |
+
batch = next(it)
|
29 |
+
image = Image.fromarray(batch[0].astype('uint8'), 'RGB')
|
30 |
+
img_byte_arr = io.BytesIO()
|
31 |
+
image.save(img_byte_arr, format='JPEG')
|
32 |
+
img_byte_arr.seek(0)
|
33 |
+
zipf.writestr(f"augmented_image_{i}_{j}.jpeg", img_byte_arr.getvalue())
|
34 |
+
|
35 |
+
# Prepare the zip file for downloading
|
36 |
+
zip_buffer.seek(0)
|
37 |
+
return zip_buffer, 'augmented_images.zip'
|
38 |
+
|
39 |
+
demo = gr.Interface(
|
40 |
+
fn=augment_images,
|
41 |
+
inputs=[gr.Files(label="Upload Images"), gr.Slider(minimum=1, maximum=10, default=5, label="Number of Augmented Images per Original")],
|
42 |
+
outputs=[gr.File(label="Download Augmented Images Zip"), 'file'],
|
43 |
+
title="Image Augmentation App",
|
44 |
+
description="Upload images to generate augmented versions. Adjust the number of augmented images per original image using the slider."
|
45 |
+
)
|
46 |
+
|
47 |
+
if __name__ == "__main__":
|
48 |
+
demo.launch()
|