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 os
|
6 |
+
import zipfile
|
7 |
+
import tempfile
|
8 |
+
|
9 |
+
def augment_images(image_file, num_duplicates):
|
10 |
+
datagen = ImageDataGenerator(
|
11 |
+
rotation_range=40,
|
12 |
+
width_shift_range=0.2,
|
13 |
+
height_shift_range=0.2,
|
14 |
+
shear_range=0.2,
|
15 |
+
zoom_range=0.2,
|
16 |
+
horizontal_flip=True,
|
17 |
+
fill_mode='nearest')
|
18 |
+
|
19 |
+
img = Image.open(image_file).convert('RGB') # Convert to RGB
|
20 |
+
img = img.resize((256, 256)) # Resize image
|
21 |
+
x = img_to_array(img) # Convert image to numpy array
|
22 |
+
x = x.reshape((1,) + x.shape) # Reshape for data generator
|
23 |
+
|
24 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
25 |
+
i = 0
|
26 |
+
for _ in datagen.flow(x, batch_size=1, save_to_dir=temp_dir, save_prefix='aug', save_format='jpeg'):
|
27 |
+
i += 1
|
28 |
+
if i >= num_duplicates:
|
29 |
+
break
|
30 |
+
|
31 |
+
# Zip the augmented images
|
32 |
+
zip_name = tempfile.mktemp(suffix='.zip')
|
33 |
+
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
34 |
+
for root, _, files in os.walk(temp_dir):
|
35 |
+
for file in files:
|
36 |
+
zipf.write(os.path.join(root, file), arcname=file)
|
37 |
+
|
38 |
+
return zip_name
|
39 |
+
|
40 |
+
iface = gr.Interface(
|
41 |
+
fn=augment_images,
|
42 |
+
inputs=[gr.Image(label="Upload Image", source="upload"), gr.Slider(minimum=1, maximum=20, default=5, label="Number of Augmented Samples")],
|
43 |
+
outputs=gr.File(label="Download Augmented Images"),
|
44 |
+
title="Image Augmentation App",
|
45 |
+
description="Upload an image to generate augmented versions. Select the number of augmented duplicates you want for the image."
|
46 |
+
)
|
47 |
+
|
48 |
+
iface.launch()
|