Zeph27 commited on
Commit
fb645d0
·
1 Parent(s): 046949a
Files changed (2) hide show
  1. app.py +133 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import zipfile
3
+ import shutil
4
+ from PIL import Image
5
+ import io
6
+ from rembg import remove
7
+ import gradio as gr
8
+
9
+ def resize_and_crop_image(image_path, target_size=(1080, 1080), crop_mode='center'):
10
+ with Image.open(image_path) as img:
11
+ width, height = img.size
12
+
13
+ # Calculate the scaling factor
14
+ scaling_factor = max(target_size[0] / width, target_size[1] / height)
15
+
16
+ # Resize the image with high-quality resampling
17
+ new_size = (int(width * scaling_factor), int(height * scaling_factor))
18
+ resized_img = img.resize(new_size, Image.LANCZOS)
19
+
20
+ if crop_mode == 'center':
21
+ left = (resized_img.width - target_size[0]) / 2
22
+ top = (resized_img.height - target_size[1]) / 2
23
+ elif crop_mode == 'top':
24
+ left = (resized_img.width - target_size[0]) / 2
25
+ top = 0
26
+ elif crop_mode == 'bottom':
27
+ left = (resized_img.width - target_size[0]) / 2
28
+ top = resized_img.height - target_size[1]
29
+ elif crop_mode == 'left':
30
+ left = 0
31
+ top = (resized_img.height - target_size[1]) / 2
32
+ elif crop_mode == 'right':
33
+ left = resized_img.width - target_size[0]
34
+ top = (resized_img.height - target_size[1]) / 2
35
+
36
+ right = left + target_size[0]
37
+ bottom = top + target_size[1]
38
+
39
+ # Crop the image
40
+ cropped_img = resized_img.crop((left, top, right, bottom))
41
+
42
+ return cropped_img
43
+
44
+ def remove_background(input_path):
45
+ with open(input_path, 'rb') as i:
46
+ input_image = i.read()
47
+ output_image = remove(input_image)
48
+ img = Image.open(io.BytesIO(output_image)).convert("RGBA")
49
+ return img
50
+
51
+ def process_images(zip_file, crop_mode='center', remove_bg='yes', progress=gr.Progress()):
52
+ # Create a temporary directory
53
+ input_folder = "temp_input"
54
+ output_folder = "temp_output"
55
+ if os.path.exists(input_folder):
56
+ shutil.rmtree(input_folder)
57
+ if os.path.exists(output_folder):
58
+ shutil.rmtree(output_folder)
59
+ os.makedirs(input_folder)
60
+ os.makedirs(output_folder)
61
+
62
+ # Extract the zip file
63
+ with zipfile.ZipFile(zip_file, 'r') as zip_ref:
64
+ zip_ref.extractall(input_folder)
65
+
66
+ processed_images = []
67
+ image_files = [f for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
68
+ total_images = len(image_files)
69
+ for idx, filename in enumerate(image_files):
70
+ image_path = os.path.join(input_folder, filename)
71
+ try:
72
+ if remove_bg == 'yes':
73
+ # Remove background
74
+ image_with_no_bg = remove_background(image_path)
75
+ temp_image_path = os.path.join(output_folder, f"temp_{filename}")
76
+ image_with_no_bg.save(temp_image_path, format='PNG')
77
+ else:
78
+ temp_image_path = image_path
79
+
80
+ # Resize and crop the image with or without background removal
81
+ new_image = resize_and_crop_image(temp_image_path, crop_mode=crop_mode)
82
+
83
+ # Save the final image
84
+ output_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}.png")
85
+ new_image.save(output_path, format='PNG')
86
+
87
+ processed_images.append(output_path)
88
+
89
+ if remove_bg == 'yes':
90
+ # Remove the temporary file
91
+ os.remove(temp_image_path)
92
+
93
+ # Update progress
94
+ progress((idx + 1) / total_images, f"{idx + 1}/{total_images} images processed")
95
+
96
+ except Exception as e:
97
+ print(f"Error processing {filename}: {e}")
98
+
99
+ # Create a zip file of the processed images
100
+ output_zip_path = "processed_images.zip"
101
+ with zipfile.ZipFile(output_zip_path, 'w') as zipf:
102
+ for file in processed_images:
103
+ zipf.write(file, os.path.basename(file))
104
+
105
+ # Return the images and the zip file path
106
+ return processed_images, output_zip_path
107
+
108
+ def gradio_interface(zip_file, crop_mode, remove_bg):
109
+ progress = gr.Progress() # Initialize progress
110
+ return process_images(zip_file.name, crop_mode, remove_bg, progress)
111
+
112
+ # Create the Gradio interface
113
+ with gr.Blocks() as iface:
114
+ gr.Markdown("# Image Background Removal and Resizing")
115
+ gr.Markdown("Upload a ZIP or RAR file containing images, choose the crop mode, and get the processed images.")
116
+
117
+ with gr.Row():
118
+ zip_file = gr.File(label="Upload ZIP/RAR file of images", file_types=[".zip", ".rar"])
119
+ crop_mode = gr.Radio(choices=["center", "top", "bottom", "left", "right"], label="Crop Mode", value="center")
120
+ remove_bg = gr.Radio(choices=["yes", "no"], label="Remove Background", value="yes")
121
+
122
+ gallery = gr.Gallery(label="Processed Images")
123
+ output_zip = gr.File(label="Download Processed Images as ZIP")
124
+
125
+ def process(zip_file, crop_mode, remove_bg):
126
+ processed_images, zip_path = gradio_interface(zip_file, crop_mode, remove_bg)
127
+ return processed_images, zip_path
128
+
129
+ process_button = gr.Button("Process Images")
130
+ process_button.click(process, inputs=[zip_file, crop_mode, remove_bg], outputs=[gallery, output_zip])
131
+
132
+ # Launch the interface
133
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==4.37.2
2
+ Pillow==10.4.0
3
+ rembg==2.0.57