muhammadsalmanalfaridzi
commited on
Commit
β’
d394950
1
Parent(s):
da8e54c
Update app.py
Browse files
app.py
CHANGED
@@ -12,7 +12,6 @@ from transformers import pipeline
|
|
12 |
import numpy as np
|
13 |
import json
|
14 |
import torch
|
15 |
-
import logging
|
16 |
|
17 |
# Load Stable Diffusion Model
|
18 |
def load_stable_diffusion_model():
|
@@ -32,32 +31,15 @@ def remove_background_rembg(input_path):
|
|
32 |
return img
|
33 |
|
34 |
def remove_background_bria(input_path):
|
35 |
-
"
|
36 |
-
|
37 |
-
|
38 |
-
# Create a segmentation pipeline
|
39 |
-
pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True)
|
40 |
|
41 |
-
# Load the
|
42 |
-
|
43 |
-
|
44 |
-
# Get the segmentation output
|
45 |
-
pillow_mask = pipe(input_image, return_mask=True) # Outputs a pillow mask
|
46 |
-
print("Mask obtained:", pillow_mask) # Debugging output
|
47 |
-
|
48 |
-
# Create an output image based on the mask
|
49 |
-
output_image = Image.new("RGBA", input_image.size)
|
50 |
-
|
51 |
-
# Use the mask to create the output image
|
52 |
-
for x in range(input_image.width):
|
53 |
-
for y in range(input_image.height):
|
54 |
-
# Assuming mask is in a binary format where foreground is True
|
55 |
-
if pillow_mask.getpixel((x, y)) > 0: # Adjust based on actual mask values
|
56 |
-
output_image.putpixel((x, y), input_image.getpixel((x, y)))
|
57 |
-
else:
|
58 |
-
output_image.putpixel((x, y), (0, 0, 0, 0)) # Set to transparent
|
59 |
|
60 |
-
|
|
|
|
|
61 |
|
62 |
# Function to process images using prompts
|
63 |
def text_to_image(prompt):
|
@@ -82,154 +64,360 @@ def text_image_to_image(input_image, prompt):
|
|
82 |
return modified_image, image_path # Return the modified image and its path
|
83 |
|
84 |
def get_bounding_box_with_threshold(image, threshold):
|
85 |
-
|
86 |
img_array = np.array(image)
|
87 |
-
|
88 |
# Get alpha channel
|
89 |
-
alpha = img_array[
|
90 |
-
|
91 |
# Find rows and columns where alpha > threshold
|
92 |
rows = np.any(alpha > threshold, axis=1)
|
93 |
cols = np.any(alpha > threshold, axis=0)
|
94 |
-
|
95 |
# Find the bounding box
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
99 |
return (left, top, right, bottom)
|
100 |
else:
|
101 |
return None
|
102 |
-
|
103 |
def position_logic(image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left, use_threshold=True):
|
104 |
-
|
105 |
-
image =
|
106 |
|
107 |
# Get the bounding box of the non-blank area with threshold
|
108 |
-
|
|
|
|
|
|
|
109 |
log = []
|
110 |
|
111 |
if bbox:
|
|
|
112 |
width, height = image.size
|
113 |
cropped_sides = []
|
114 |
-
|
115 |
-
|
116 |
-
#
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
# Crop the image to the bounding box
|
133 |
image = image.crop(bbox)
|
134 |
log.append({"action": "crop", "bbox": [str(bbox[0]), str(bbox[1]), str(bbox[2]), str(bbox[3])]})
|
135 |
|
136 |
-
# Calculate new size to expand the image
|
137 |
target_width, target_height = canvas_size
|
138 |
aspect_ratio = image.width / image.height
|
139 |
|
140 |
-
# Handling image positioning and resizing based on cropped sides
|
141 |
if len(cropped_sides) == 4:
|
142 |
-
#
|
143 |
if aspect_ratio > 1: # Landscape
|
144 |
new_height = target_height
|
145 |
new_width = int(new_height * aspect_ratio)
|
146 |
left = (new_width - target_width) // 2
|
147 |
-
image = image.resize((new_width, new_height), Image.LANCZOS)
|
|
|
148 |
else: # Portrait or square
|
149 |
new_width = target_width
|
150 |
new_height = int(new_width / aspect_ratio)
|
151 |
top = (new_height - target_height) // 2
|
152 |
-
image = image.resize((new_width, new_height), Image.LANCZOS)
|
|
|
153 |
log.append({"action": "center_crop_resize", "new_size": f"{target_width}x{target_height}"})
|
154 |
x, y = 0, 0
|
155 |
elif not cropped_sides:
|
156 |
-
#
|
157 |
new_height = target_height - padding_top - padding_bottom
|
158 |
new_width = int(new_height * aspect_ratio)
|
|
|
159 |
if new_width > target_width - padding_left - padding_right:
|
|
|
160 |
new_width = target_width - padding_left - padding_right
|
161 |
new_height = int(new_width / aspect_ratio)
|
162 |
-
|
|
|
163 |
image = image.resize((new_width, new_height), Image.LANCZOS)
|
164 |
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
|
|
165 |
x = (target_width - new_width) // 2
|
166 |
y = target_height - new_height - padding_bottom
|
167 |
else:
|
168 |
-
#
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
184 |
|
185 |
return log, image, x, y
|
186 |
|
187 |
-
# Constants for canvas sizes and paddings
|
188 |
-
CANVAS_SIZES = {
|
189 |
-
'Rox': ((1080, 1080), (112, 125, 116, 125)),
|
190 |
-
'Columbia': ((730, 610), (30, 105, 35, 105)),
|
191 |
-
'Zalora': ((763, 1100), (50, 50, 200, 50))
|
192 |
-
}
|
193 |
-
|
194 |
def process_single_image(image_path, output_folder, bg_method, canvas_size_name, output_format, bg_choice, custom_color, watermark_path=None):
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
try:
|
211 |
-
|
212 |
-
filename = os.path.basename(image_path)
|
213 |
-
logging.info(f"Processing image: {filename}")
|
214 |
-
|
215 |
-
# Remove background
|
216 |
-
image_with_no_bg = Image.open(image_path).convert("RGBA")
|
217 |
if bg_method == 'rembg':
|
218 |
image_with_no_bg = remove_background_rembg(image_path)
|
219 |
elif bg_method == 'bria':
|
220 |
image_with_no_bg = remove_background_bria(image_path)
|
221 |
-
elif bg_method ==
|
222 |
-
|
223 |
-
|
224 |
-
raise ValueError("Invalid background method specified.")
|
225 |
-
|
226 |
-
# Temporary file for processed image
|
227 |
temp_image_path = os.path.join(output_folder, f"temp_{filename}")
|
228 |
image_with_no_bg.save(temp_image_path, format='PNG')
|
229 |
|
230 |
log, new_image, x, y = position_logic(temp_image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left)
|
231 |
|
232 |
-
# Create canvas
|
233 |
if bg_choice == 'white':
|
234 |
canvas = Image.new("RGBA", canvas_size, "WHITE")
|
235 |
elif bg_choice == 'custom':
|
@@ -241,62 +429,45 @@ def process_single_image(image_path, output_folder, bg_method, canvas_size_name,
|
|
241 |
canvas.paste(new_image, (x, y), new_image)
|
242 |
log.append({"action": "paste", "position": [str(x), str(y)]})
|
243 |
|
244 |
-
# Add
|
245 |
-
if
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
canvas_width, canvas_height = canvas.size
|
250 |
-
# Hitung posisi (x, y) untuk watermark
|
251 |
-
x = (canvas_width - watermark_width) // 2
|
252 |
-
y = (canvas_height - watermark_height) // 2
|
253 |
-
# Tempelkan watermark
|
254 |
-
canvas.paste(watermark, (x, y), watermark)
|
255 |
-
log.append({"action": "add_watermark"})
|
256 |
|
257 |
-
# Determine output format
|
258 |
output_ext = 'jpg' if output_format == 'JPG' else 'png'
|
259 |
output_filename = f"{os.path.splitext(filename)[0]}.{output_ext}"
|
260 |
output_path = os.path.join(output_folder, output_filename)
|
261 |
|
262 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
263 |
if output_format == 'JPG':
|
264 |
-
canvas.convert('RGB')
|
|
|
265 |
else:
|
266 |
canvas.save(output_path, format='PNG')
|
267 |
|
268 |
-
# Clean up temporary file
|
269 |
os.remove(temp_image_path)
|
270 |
|
271 |
-
|
272 |
return [(output_path, image_path)], log
|
273 |
|
274 |
except Exception as e:
|
275 |
-
|
276 |
return None, None
|
277 |
-
|
278 |
-
|
279 |
-
|
|
|
280 |
|
281 |
def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_size='Rox', output_format='PNG', bg_choice='transparent', custom_color="#ffffff", num_workers=4, progress=gr.Progress()):
|
282 |
-
"""Processes images by removing backgrounds and applying various transformations.
|
283 |
-
|
284 |
-
Args:
|
285 |
-
input_files (str or list): Path to a ZIP file or a list of image paths.
|
286 |
-
bg_method (str): Background removal method ('rembg' or 'bria').
|
287 |
-
watermark_path (str, optional): Path to a watermark image.
|
288 |
-
canvas_size (str): Name of the canvas size.
|
289 |
-
output_format (str): Desired output format ('PNG' or 'JPG').
|
290 |
-
bg_choice (str): Background choice ('transparent', 'white', or 'custom').
|
291 |
-
custom_color (str): Custom background color in hex format.
|
292 |
-
num_workers (int): Number of parallel workers for processing.
|
293 |
-
progress (gr.Progress): Progress tracking interface.
|
294 |
-
|
295 |
-
Returns:
|
296 |
-
tuple: A tuple containing original images, processed images, output zip path, and total processing time.
|
297 |
-
"""
|
298 |
start_time = time.time()
|
299 |
-
|
300 |
output_folder = "processed_images"
|
301 |
if os.path.exists(output_folder):
|
302 |
shutil.rmtree(output_folder)
|
@@ -305,8 +476,6 @@ def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_s
|
|
305 |
processed_images = []
|
306 |
original_images = []
|
307 |
all_logs = []
|
308 |
-
|
309 |
-
image_files = []
|
310 |
|
311 |
if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):
|
312 |
# Handle zip file
|
@@ -318,19 +487,20 @@ def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_s
|
|
318 |
try:
|
319 |
with zipfile.ZipFile(input_files, 'r') as zip_ref:
|
320 |
zip_ref.extractall(input_folder)
|
321 |
-
image_files = [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp'))]
|
322 |
except zipfile.BadZipFile as e:
|
323 |
-
|
324 |
return [], None, 0
|
|
|
|
|
325 |
elif isinstance(input_files, list):
|
326 |
# Handle multiple files
|
327 |
image_files = input_files
|
328 |
else:
|
329 |
# Handle single file
|
330 |
image_files = [input_files]
|
331 |
-
|
332 |
total_images = len(image_files)
|
333 |
-
|
334 |
|
335 |
avg_processing_time = 0
|
336 |
with ThreadPoolExecutor(max_workers=num_workers) as executor:
|
@@ -341,22 +511,29 @@ def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_s
|
|
341 |
result, log = future.result()
|
342 |
end_time_image = time.time()
|
343 |
image_processing_time = end_time_image - start_time_image
|
344 |
-
|
345 |
# Update average processing time
|
346 |
avg_processing_time = (avg_processing_time * idx + image_processing_time) / (idx + 1)
|
347 |
-
|
348 |
if result:
|
349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
350 |
original_images.append(future_to_image[future])
|
351 |
all_logs.append({os.path.basename(future_to_image[future]): log})
|
352 |
-
|
353 |
# Estimate remaining time
|
354 |
remaining_images = total_images - (idx + 1)
|
355 |
estimated_remaining_time = remaining_images * avg_processing_time
|
356 |
-
|
357 |
progress((idx + 1) / total_images, f"{idx + 1}/{total_images} images processed. Estimated time remaining: {estimated_remaining_time:.2f} seconds")
|
358 |
except Exception as e:
|
359 |
-
|
360 |
|
361 |
output_zip_path = "processed_images.zip"
|
362 |
with zipfile.ZipFile(output_zip_path, 'w') as zipf:
|
@@ -366,40 +543,35 @@ def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_s
|
|
366 |
# Write the comprehensive log for all images
|
367 |
with open(os.path.join(output_folder, 'process_log.json'), 'w') as log_file:
|
368 |
json.dump(all_logs, log_file, indent=4)
|
369 |
-
|
370 |
|
371 |
end_time = time.time()
|
372 |
processing_time = end_time - start_time
|
373 |
-
|
374 |
-
|
375 |
return original_images, processed_images, output_zip_path, processing_time
|
376 |
|
377 |
-
# Set up logging
|
378 |
-
logging.basicConfig(level=logging.INFO)
|
379 |
-
|
380 |
def gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):
|
381 |
-
"""Handles input files and processes them accordingly."""
|
382 |
progress = gr.Progress()
|
383 |
watermark_path = watermark.name if watermark else None
|
384 |
-
|
385 |
-
# Check
|
386 |
if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):
|
387 |
-
|
388 |
elif isinstance(input_files, list):
|
389 |
return process_images(input_files, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)
|
390 |
else:
|
391 |
return process_images(input_files.name, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)
|
392 |
|
393 |
def show_color_picker(bg_choice):
|
394 |
-
|
395 |
-
|
|
|
396 |
|
397 |
def update_compare(evt: gr.SelectData):
|
398 |
-
"""Updates the displayed images and their ratios when a processed image is selected."""
|
399 |
if isinstance(evt.value, dict) and 'caption' in evt.value:
|
400 |
-
input_path = evt.value['caption']
|
401 |
output_path = evt.value['image']['path']
|
402 |
-
|
403 |
# Open the original and processed images
|
404 |
original_img = Image.open(input_path)
|
405 |
processed_img = Image.open(output_path)
|
@@ -408,25 +580,63 @@ def update_compare(evt: gr.SelectData):
|
|
408 |
original_ratio = f"{original_img.width}x{original_img.height}"
|
409 |
processed_ratio = f"{processed_img.width}x{processed_img.height}"
|
410 |
|
411 |
-
return
|
412 |
-
gr.update(value=output_path),
|
413 |
-
gr.update(value=original_ratio),
|
414 |
-
gr.update(value=processed_ratio)
|
415 |
-
)
|
416 |
else:
|
417 |
-
|
418 |
-
return (gr.update(value=None),)
|
419 |
|
420 |
def process(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
430 |
|
431 |
with gr.Blocks(theme="NoCrypt/miku@1.2.2") as iface:
|
432 |
gr.Markdown("# π¨ Creative Image Suite: Generate, Modify, and Enhance Your Visuals")
|
@@ -498,7 +708,7 @@ with gr.Blocks(theme="NoCrypt/miku@1.2.2") as iface:
|
|
498 |
num_workers = gr.Slider(minimum=1, maximum=16, step=1, label="Number of Workers", value=5)
|
499 |
|
500 |
with gr.Row():
|
501 |
-
bg_method = gr.Radio(choices=["bria", "rembg",
|
502 |
bg_choice = gr.Radio(choices=["transparent", "white", "custom"], label="Background Choice", value="white")
|
503 |
custom_color = gr.ColorPicker(label="Custom Background Color", value="#ffffff", visible=False)
|
504 |
|
|
|
12 |
import numpy as np
|
13 |
import json
|
14 |
import torch
|
|
|
15 |
|
16 |
# Load Stable Diffusion Model
|
17 |
def load_stable_diffusion_model():
|
|
|
31 |
return img
|
32 |
|
33 |
def remove_background_bria(input_path):
|
34 |
+
print(f"Removing background using bria for image: {input_path}")
|
35 |
+
device = 0 if torch.cuda.is_available() else -1
|
|
|
|
|
|
|
36 |
|
37 |
+
# Load the segmentation model
|
38 |
+
pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True, device=device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
# Process the image
|
41 |
+
result = pipe(input_path)
|
42 |
+
return result
|
43 |
|
44 |
# Function to process images using prompts
|
45 |
def text_to_image(prompt):
|
|
|
64 |
return modified_image, image_path # Return the modified image and its path
|
65 |
|
66 |
def get_bounding_box_with_threshold(image, threshold):
|
67 |
+
# Convert image to numpy array
|
68 |
img_array = np.array(image)
|
69 |
+
|
70 |
# Get alpha channel
|
71 |
+
alpha = img_array[:,:,3]
|
72 |
+
|
73 |
# Find rows and columns where alpha > threshold
|
74 |
rows = np.any(alpha > threshold, axis=1)
|
75 |
cols = np.any(alpha > threshold, axis=0)
|
76 |
+
|
77 |
# Find the bounding box
|
78 |
+
top, bottom = np.where(rows)[0][[0, -1]]
|
79 |
+
left, right = np.where(cols)[0][[0, -1]]
|
80 |
+
|
81 |
+
if left < right and top < bottom:
|
82 |
return (left, top, right, bottom)
|
83 |
else:
|
84 |
return None
|
85 |
+
|
86 |
def position_logic(image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left, use_threshold=True):
|
87 |
+
image = Image.open(image_path)
|
88 |
+
image = image.convert("RGBA")
|
89 |
|
90 |
# Get the bounding box of the non-blank area with threshold
|
91 |
+
if use_threshold:
|
92 |
+
bbox = get_bounding_box_with_threshold(image, threshold=10)
|
93 |
+
else:
|
94 |
+
bbox = image.getbbox()
|
95 |
log = []
|
96 |
|
97 |
if bbox:
|
98 |
+
# Check 1 pixel around the image for non-transparent pixels
|
99 |
width, height = image.size
|
100 |
cropped_sides = []
|
101 |
+
|
102 |
+
# Define tolerance for transparency
|
103 |
+
tolerance = 30 # Adjust this value as needed
|
104 |
+
|
105 |
+
# Check top edge
|
106 |
+
if any(image.getpixel((x, 0))[3] > tolerance for x in range(width)):
|
107 |
+
cropped_sides.append("top")
|
108 |
+
|
109 |
+
# Check bottom edge
|
110 |
+
if any(image.getpixel((x, height-1))[3] > tolerance for x in range(width)):
|
111 |
+
cropped_sides.append("bottom")
|
112 |
+
|
113 |
+
# Check left edge
|
114 |
+
if any(image.getpixel((0, y))[3] > tolerance for y in range(height)):
|
115 |
+
cropped_sides.append("left")
|
116 |
+
|
117 |
+
# Check right edge
|
118 |
+
if any(image.getpixel((width-1, y))[3] > tolerance for y in range(height)):
|
119 |
+
cropped_sides.append("right")
|
120 |
+
|
121 |
+
if cropped_sides:
|
122 |
+
info_message = f"Info for {os.path.basename(image_path)}: The following sides of the image may contain cropped objects: {', '.join(cropped_sides)}"
|
123 |
+
print(info_message)
|
124 |
+
log.append({"info": info_message})
|
125 |
+
else:
|
126 |
+
info_message = f"Info for {os.path.basename(image_path)}: The image is not cropped."
|
127 |
+
print(info_message)
|
128 |
+
log.append({"info": info_message})
|
129 |
|
130 |
# Crop the image to the bounding box
|
131 |
image = image.crop(bbox)
|
132 |
log.append({"action": "crop", "bbox": [str(bbox[0]), str(bbox[1]), str(bbox[2]), str(bbox[3])]})
|
133 |
|
134 |
+
# Calculate the new size to expand the image
|
135 |
target_width, target_height = canvas_size
|
136 |
aspect_ratio = image.width / image.height
|
137 |
|
|
|
138 |
if len(cropped_sides) == 4:
|
139 |
+
# If the image is cropped on all sides, center crop it to fit the canvas
|
140 |
if aspect_ratio > 1: # Landscape
|
141 |
new_height = target_height
|
142 |
new_width = int(new_height * aspect_ratio)
|
143 |
left = (new_width - target_width) // 2
|
144 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
145 |
+
image = image.crop((left, 0, left + target_width, target_height))
|
146 |
else: # Portrait or square
|
147 |
new_width = target_width
|
148 |
new_height = int(new_width / aspect_ratio)
|
149 |
top = (new_height - target_height) // 2
|
150 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
151 |
+
image = image.crop((0, top, target_width, top + target_height))
|
152 |
log.append({"action": "center_crop_resize", "new_size": f"{target_width}x{target_height}"})
|
153 |
x, y = 0, 0
|
154 |
elif not cropped_sides:
|
155 |
+
# If the image is not cropped, expand it from center until it touches the padding
|
156 |
new_height = target_height - padding_top - padding_bottom
|
157 |
new_width = int(new_height * aspect_ratio)
|
158 |
+
|
159 |
if new_width > target_width - padding_left - padding_right:
|
160 |
+
# If width exceeds available space, adjust based on width
|
161 |
new_width = target_width - padding_left - padding_right
|
162 |
new_height = int(new_width / aspect_ratio)
|
163 |
+
|
164 |
+
# Resize the image
|
165 |
image = image.resize((new_width, new_height), Image.LANCZOS)
|
166 |
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
167 |
+
|
168 |
x = (target_width - new_width) // 2
|
169 |
y = target_height - new_height - padding_bottom
|
170 |
else:
|
171 |
+
# New logic for handling cropped top and left, or top and right
|
172 |
+
if set(cropped_sides) == {"top", "left"} or set(cropped_sides) == {"top", "right"}:
|
173 |
+
new_height = target_height - padding_bottom
|
174 |
+
new_width = int(new_height * aspect_ratio)
|
175 |
+
|
176 |
+
# If new width exceeds canvas width, adjust based on width
|
177 |
+
if new_width > target_width:
|
178 |
+
new_width = target_width
|
179 |
+
new_height = int(new_width / aspect_ratio)
|
180 |
+
|
181 |
+
# Resize the image
|
182 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
183 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
184 |
+
|
185 |
+
# Set position
|
186 |
+
if "left" in cropped_sides:
|
187 |
+
x = 0
|
188 |
+
else: # right in cropped_sides
|
189 |
+
x = target_width - new_width
|
190 |
+
y = 0
|
191 |
+
|
192 |
+
# If the resized image is taller than the canvas minus padding, crop from the bottom
|
193 |
+
if new_height > target_height - padding_bottom:
|
194 |
+
crop_bottom = new_height - (target_height - padding_bottom)
|
195 |
+
image = image.crop((0, 0, new_width, new_height - crop_bottom))
|
196 |
+
new_height = target_height - padding_bottom
|
197 |
+
log.append({"action": "crop_vertical", "bottom_pixels_removed": str(crop_bottom)})
|
198 |
+
|
199 |
+
log.append({"action": "position", "x": str(x), "y": str(y)})
|
200 |
+
elif set(cropped_sides) == {"bottom", "left"} or set(cropped_sides) == {"bottom", "right"}:
|
201 |
+
# Handle bottom & left or bottom & right cropped images
|
202 |
+
new_height = target_height - padding_top
|
203 |
+
new_width = int(new_height * aspect_ratio)
|
204 |
+
|
205 |
+
# If new width exceeds canvas width, adjust based on width
|
206 |
+
if new_width > target_width - padding_left - padding_right:
|
207 |
+
new_width = target_width - padding_left - padding_right
|
208 |
+
new_height = int(new_width / aspect_ratio)
|
209 |
+
|
210 |
+
# Resize the image without cropping or stretching
|
211 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
212 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
213 |
+
|
214 |
+
# Set position
|
215 |
+
if "left" in cropped_sides:
|
216 |
+
x = 0
|
217 |
+
else: # right in cropped_sides
|
218 |
+
x = target_width - new_width
|
219 |
+
y = target_height - new_height
|
220 |
+
|
221 |
+
log.append({"action": "position", "x": str(x), "y": str(y)})
|
222 |
+
elif set(cropped_sides) == {"bottom", "left", "right"}:
|
223 |
+
# Expand the image from the center
|
224 |
+
new_width = target_width
|
225 |
+
new_height = int(new_width / aspect_ratio)
|
226 |
+
|
227 |
+
if new_height < target_height:
|
228 |
+
new_height = target_height
|
229 |
+
new_width = int(new_height * aspect_ratio)
|
230 |
+
|
231 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
232 |
+
|
233 |
+
# Crop to fit the canvas
|
234 |
+
left = (new_width - target_width) // 2
|
235 |
+
top = 0
|
236 |
+
image = image.crop((left, top, left + target_width, top + target_height))
|
237 |
+
|
238 |
+
log.append({"action": "expand_and_crop", "new_size": f"{target_width}x{target_height}"})
|
239 |
+
x, y = 0, 0
|
240 |
+
elif cropped_sides == ["top"]:
|
241 |
+
# New logic for handling only top-cropped images
|
242 |
+
if image.width > image.height:
|
243 |
+
new_width = target_width
|
244 |
+
new_height = int(target_width / aspect_ratio)
|
245 |
+
else:
|
246 |
+
new_height = target_height - padding_bottom
|
247 |
+
new_width = int(new_height * aspect_ratio)
|
248 |
+
|
249 |
+
# Resize the image
|
250 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
251 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
252 |
+
|
253 |
+
x = (target_width - new_width) // 2
|
254 |
+
y = 0 # Align to top
|
255 |
+
|
256 |
+
# Apply padding only to non-cropped sides
|
257 |
+
x = max(padding_left, min(x, target_width - new_width - padding_right))
|
258 |
+
elif cropped_sides in [["right"], ["left"]]:
|
259 |
+
# New logic for handling only right-cropped or left-cropped images
|
260 |
+
if image.width > image.height:
|
261 |
+
new_width = target_width - max(padding_left, padding_right)
|
262 |
+
new_height = int(new_width / aspect_ratio)
|
263 |
+
else:
|
264 |
+
new_height = target_height - padding_top - padding_bottom
|
265 |
+
new_width = int(new_height * aspect_ratio)
|
266 |
+
|
267 |
+
# Resize the image
|
268 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
269 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
270 |
+
|
271 |
+
if cropped_sides == ["right"]:
|
272 |
+
x = target_width - new_width # Align to right
|
273 |
+
else: # cropped_sides == ["left"]
|
274 |
+
x = 0 # Align to left
|
275 |
+
y = target_height - new_height - padding_bottom # Respect bottom padding
|
276 |
+
|
277 |
+
# Ensure top padding is respected
|
278 |
+
if y < padding_top:
|
279 |
+
y = padding_top
|
280 |
+
|
281 |
+
log.append({"action": "position", "x": str(x), "y": str(y)})
|
282 |
+
elif set(cropped_sides) == {"left", "right"}:
|
283 |
+
# Logic for handling images cropped on both left and right sides
|
284 |
+
new_width = target_width # Expand to full width of canvas
|
285 |
+
|
286 |
+
# Calculate the aspect ratio of the original image
|
287 |
+
aspect_ratio = image.width / image.height
|
288 |
+
|
289 |
+
# Calculate the new height while maintaining aspect ratio
|
290 |
+
new_height = int(new_width / aspect_ratio)
|
291 |
+
|
292 |
+
# Resize the image
|
293 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
294 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
295 |
+
|
296 |
+
# Set horizontal position (always 0 as it spans full width)
|
297 |
+
x = 0
|
298 |
+
|
299 |
+
# Calculate vertical position to respect bottom padding
|
300 |
+
y = target_height - new_height - padding_bottom
|
301 |
+
|
302 |
+
# If the resized image is taller than the canvas, crop from the top only
|
303 |
+
if new_height > target_height - padding_bottom:
|
304 |
+
crop_top = new_height - (target_height - padding_bottom)
|
305 |
+
image = image.crop((0, crop_top, new_width, new_height))
|
306 |
+
new_height = target_height - padding_bottom
|
307 |
+
y = 0
|
308 |
+
log.append({"action": "crop_vertical", "top_pixels_removed": str(crop_top)})
|
309 |
+
else:
|
310 |
+
# Align the image to the bottom with padding
|
311 |
+
y = target_height - new_height - padding_bottom
|
312 |
+
|
313 |
+
log.append({"action": "position", "x": str(x), "y": str(y)})
|
314 |
+
elif cropped_sides == ["bottom"]:
|
315 |
+
# Logic for handling images cropped on the bottom side
|
316 |
+
# Calculate the aspect ratio of the original image
|
317 |
+
aspect_ratio = image.width / image.height
|
318 |
+
|
319 |
+
if aspect_ratio < 1: # Portrait orientation
|
320 |
+
new_height = target_height - padding_top # Full height with top padding
|
321 |
+
new_width = int(new_height * aspect_ratio)
|
322 |
+
|
323 |
+
# If the new width exceeds the canvas width, adjust it
|
324 |
+
if new_width > target_width:
|
325 |
+
new_width = target_width
|
326 |
+
new_height = int(new_width / aspect_ratio)
|
327 |
+
else: # Landscape orientation
|
328 |
+
new_width = target_width - padding_left - padding_right
|
329 |
+
new_height = int(new_width / aspect_ratio)
|
330 |
+
|
331 |
+
# If the new height exceeds the canvas height, adjust it
|
332 |
+
if new_height > target_height:
|
333 |
+
new_height = target_height
|
334 |
+
new_width = int(new_height * aspect_ratio)
|
335 |
+
|
336 |
+
# Resize the image
|
337 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
338 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
339 |
+
|
340 |
+
# Set horizontal position (centered)
|
341 |
+
x = (target_width - new_width) // 2
|
342 |
+
|
343 |
+
# Set vertical position (touching bottom edge for all cases)
|
344 |
+
y = target_height - new_height
|
345 |
+
|
346 |
+
log.append({"action": "position", "x": str(x), "y": str(y)})
|
347 |
+
else:
|
348 |
+
# Use the original resizing logic for other partially cropped images
|
349 |
+
if image.width > image.height:
|
350 |
+
new_width = target_width
|
351 |
+
new_height = int(target_width / aspect_ratio)
|
352 |
+
else:
|
353 |
+
new_height = target_height
|
354 |
+
new_width = int(target_height * aspect_ratio)
|
355 |
+
|
356 |
+
# Resize the image
|
357 |
+
image = image.resize((new_width, new_height), Image.LANCZOS)
|
358 |
+
log.append({"action": "resize", "new_width": str(new_width), "new_height": str(new_height)})
|
359 |
+
|
360 |
+
# Center horizontally for all images
|
361 |
+
x = (target_width - new_width) // 2
|
362 |
+
y = target_height - new_height - padding_bottom
|
363 |
+
|
364 |
+
# Adjust positions for cropped sides
|
365 |
+
if "top" in cropped_sides:
|
366 |
+
y = 0
|
367 |
+
elif "bottom" in cropped_sides:
|
368 |
+
y = target_height - new_height
|
369 |
+
if "left" in cropped_sides:
|
370 |
+
x = 0
|
371 |
+
elif "right" in cropped_sides:
|
372 |
+
x = target_width - new_width
|
373 |
+
|
374 |
+
# Apply padding only to non-cropped sides, but keep horizontal centering
|
375 |
+
if "left" not in cropped_sides and "right" not in cropped_sides:
|
376 |
+
x = (target_width - new_width) // 2 # Always center horizontally
|
377 |
+
if "top" not in cropped_sides and "bottom" not in cropped_sides:
|
378 |
+
y = max(padding_top, min(y, target_height - new_height - padding_bottom))
|
379 |
|
380 |
return log, image, x, y
|
381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
382 |
def process_single_image(image_path, output_folder, bg_method, canvas_size_name, output_format, bg_choice, custom_color, watermark_path=None):
|
383 |
+
add_padding_line = False
|
384 |
+
|
385 |
+
if canvas_size_name == 'Rox':
|
386 |
+
canvas_size = (1080, 1080)
|
387 |
+
padding_top = 112
|
388 |
+
padding_right = 125
|
389 |
+
padding_bottom = 116
|
390 |
+
padding_left = 125
|
391 |
+
elif canvas_size_name == 'Columbia':
|
392 |
+
canvas_size = (730, 610)
|
393 |
+
padding_top = 30
|
394 |
+
padding_right = 105
|
395 |
+
padding_bottom = 35
|
396 |
+
padding_left = 105
|
397 |
+
elif canvas_size_name == 'Zalora':
|
398 |
+
canvas_size = (763, 1100)
|
399 |
+
padding_top = 50
|
400 |
+
padding_right = 50
|
401 |
+
padding_bottom = 200
|
402 |
+
padding_left = 50
|
403 |
+
|
404 |
+
|
405 |
+
filename = os.path.basename(image_path)
|
406 |
try:
|
407 |
+
print(f"Processing image: {filename}")
|
|
|
|
|
|
|
|
|
|
|
408 |
if bg_method == 'rembg':
|
409 |
image_with_no_bg = remove_background_rembg(image_path)
|
410 |
elif bg_method == 'bria':
|
411 |
image_with_no_bg = remove_background_bria(image_path)
|
412 |
+
elif bg_method == None:
|
413 |
+
image_with_no_bg = Image.open(image_path)
|
414 |
+
|
|
|
|
|
|
|
415 |
temp_image_path = os.path.join(output_folder, f"temp_{filename}")
|
416 |
image_with_no_bg.save(temp_image_path, format='PNG')
|
417 |
|
418 |
log, new_image, x, y = position_logic(temp_image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left)
|
419 |
|
420 |
+
# Create a new canvas with the appropriate background
|
421 |
if bg_choice == 'white':
|
422 |
canvas = Image.new("RGBA", canvas_size, "WHITE")
|
423 |
elif bg_choice == 'custom':
|
|
|
429 |
canvas.paste(new_image, (x, y), new_image)
|
430 |
log.append({"action": "paste", "position": [str(x), str(y)]})
|
431 |
|
432 |
+
# Add visible black line for padding when background is not transparent
|
433 |
+
if add_padding_line:
|
434 |
+
draw = ImageDraw.Draw(canvas)
|
435 |
+
draw.rectangle([padding_left, padding_top, canvas_size[0] - padding_right, canvas_size[1] - padding_bottom], outline="black", width=5)
|
436 |
+
log.append({"action": "add_padding_line"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
437 |
|
|
|
438 |
output_ext = 'jpg' if output_format == 'JPG' else 'png'
|
439 |
output_filename = f"{os.path.splitext(filename)[0]}.{output_ext}"
|
440 |
output_path = os.path.join(output_folder, output_filename)
|
441 |
|
442 |
+
# Apply watermark only if the filename ends with "_01" and watermark_path is provided
|
443 |
+
if os.path.splitext(filename)[0].endswith("_01") and watermark_path:
|
444 |
+
watermark = Image.open(watermark_path).convert("RGBA")
|
445 |
+
canvas = canvas.convert("RGBA")
|
446 |
+
canvas.paste(watermark, (0, 0), watermark)
|
447 |
+
log.append({"action": "add_watermark"})
|
448 |
+
|
449 |
if output_format == 'JPG':
|
450 |
+
canvas = canvas.convert('RGB')
|
451 |
+
canvas.save(output_path, format='JPEG')
|
452 |
else:
|
453 |
canvas.save(output_path, format='PNG')
|
454 |
|
|
|
455 |
os.remove(temp_image_path)
|
456 |
|
457 |
+
print(f"Processed image path: {output_path}")
|
458 |
return [(output_path, image_path)], log
|
459 |
|
460 |
except Exception as e:
|
461 |
+
print(f"Error processing {filename}: {e}")
|
462 |
return None, None
|
463 |
+
|
464 |
+
def remove_extension(filename):
|
465 |
+
# Regular expression to match any extension at the end of the string
|
466 |
+
return re.sub(r'\.[^.]+$', '', filename)
|
467 |
|
468 |
def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_size='Rox', output_format='PNG', bg_choice='transparent', custom_color="#ffffff", num_workers=4, progress=gr.Progress()):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
469 |
start_time = time.time()
|
470 |
+
|
471 |
output_folder = "processed_images"
|
472 |
if os.path.exists(output_folder):
|
473 |
shutil.rmtree(output_folder)
|
|
|
476 |
processed_images = []
|
477 |
original_images = []
|
478 |
all_logs = []
|
|
|
|
|
479 |
|
480 |
if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):
|
481 |
# Handle zip file
|
|
|
487 |
try:
|
488 |
with zipfile.ZipFile(input_files, 'r') as zip_ref:
|
489 |
zip_ref.extractall(input_folder)
|
|
|
490 |
except zipfile.BadZipFile as e:
|
491 |
+
print(f"Error extracting zip file: {e}")
|
492 |
return [], None, 0
|
493 |
+
|
494 |
+
image_files = [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp'))]
|
495 |
elif isinstance(input_files, list):
|
496 |
# Handle multiple files
|
497 |
image_files = input_files
|
498 |
else:
|
499 |
# Handle single file
|
500 |
image_files = [input_files]
|
501 |
+
|
502 |
total_images = len(image_files)
|
503 |
+
print(f"Total images to process: {total_images}")
|
504 |
|
505 |
avg_processing_time = 0
|
506 |
with ThreadPoolExecutor(max_workers=num_workers) as executor:
|
|
|
511 |
result, log = future.result()
|
512 |
end_time_image = time.time()
|
513 |
image_processing_time = end_time_image - start_time_image
|
514 |
+
|
515 |
# Update average processing time
|
516 |
avg_processing_time = (avg_processing_time * idx + image_processing_time) / (idx + 1)
|
|
|
517 |
if result:
|
518 |
+
if watermark_path:
|
519 |
+
get_name = future_to_image[future].split('/')
|
520 |
+
get_name = remove_extension(get_name[len(get_name)-1])
|
521 |
+
twibbon_input = f'{get_name}.png' if output_format == 'PNG' else f'{get_name}.jpg'
|
522 |
+
twibbon_output_path = os.path.join(output_folder, f'result_{start_time_image}.png')
|
523 |
+
add_twibbon(f'processed_images/{twibbon_input}', watermark_path, twibbon_output_path)
|
524 |
+
processed_images.append((twibbon_output_path, twibbon_output_path))
|
525 |
+
else:
|
526 |
+
processed_images.extend(result)
|
527 |
original_images.append(future_to_image[future])
|
528 |
all_logs.append({os.path.basename(future_to_image[future]): log})
|
529 |
+
|
530 |
# Estimate remaining time
|
531 |
remaining_images = total_images - (idx + 1)
|
532 |
estimated_remaining_time = remaining_images * avg_processing_time
|
533 |
+
|
534 |
progress((idx + 1) / total_images, f"{idx + 1}/{total_images} images processed. Estimated time remaining: {estimated_remaining_time:.2f} seconds")
|
535 |
except Exception as e:
|
536 |
+
print(f"Error processing image {future_to_image[future]}: {e}")
|
537 |
|
538 |
output_zip_path = "processed_images.zip"
|
539 |
with zipfile.ZipFile(output_zip_path, 'w') as zipf:
|
|
|
543 |
# Write the comprehensive log for all images
|
544 |
with open(os.path.join(output_folder, 'process_log.json'), 'w') as log_file:
|
545 |
json.dump(all_logs, log_file, indent=4)
|
546 |
+
print("Comprehensive log saved to", os.path.join(output_folder, 'process_log.json'))
|
547 |
|
548 |
end_time = time.time()
|
549 |
processing_time = end_time - start_time
|
550 |
+
print(f"Processing time: {processing_time} seconds")
|
|
|
551 |
return original_images, processed_images, output_zip_path, processing_time
|
552 |
|
|
|
|
|
|
|
553 |
def gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):
|
|
|
554 |
progress = gr.Progress()
|
555 |
watermark_path = watermark.name if watermark else None
|
556 |
+
|
557 |
+
# Check input_files, is it single image, list image, or zip/rar
|
558 |
if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):
|
559 |
+
return process_images(input_files, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)
|
560 |
elif isinstance(input_files, list):
|
561 |
return process_images(input_files, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)
|
562 |
else:
|
563 |
return process_images(input_files.name, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)
|
564 |
|
565 |
def show_color_picker(bg_choice):
|
566 |
+
if bg_choice == 'custom':
|
567 |
+
return gr.update(visible=True)
|
568 |
+
return gr.update(visible=False)
|
569 |
|
570 |
def update_compare(evt: gr.SelectData):
|
|
|
571 |
if isinstance(evt.value, dict) and 'caption' in evt.value:
|
572 |
+
input_path = evt.value['caption']
|
573 |
output_path = evt.value['image']['path']
|
574 |
+
input_path = input_path.split("Input: ")[-1]
|
575 |
# Open the original and processed images
|
576 |
original_img = Image.open(input_path)
|
577 |
processed_img = Image.open(output_path)
|
|
|
580 |
original_ratio = f"{original_img.width}x{original_img.height}"
|
581 |
processed_ratio = f"{processed_img.width}x{processed_img.height}"
|
582 |
|
583 |
+
return gr.update(value=input_path), gr.update(value=output_path), gr.update(value=original_ratio), gr.update(value=processed_ratio)
|
|
|
|
|
|
|
|
|
584 |
else:
|
585 |
+
print("No caption found in selection")
|
586 |
+
return gr.update(value=None), gr.update(value=None), gr.update(value=None), gr.update(value=None)
|
587 |
|
588 |
def process(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):
|
589 |
+
_, processed_images, zip_path, time_taken = gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers)
|
590 |
+
processed_images_with_captions = [(img, f"Input: {caption}") for img, caption in processed_images]
|
591 |
+
return processed_images_with_captions, zip_path, f"{time_taken:.2f} seconds"
|
592 |
+
|
593 |
+
def add_twibbon(image_path, twibbon_path, output_path):
|
594 |
+
# Open the original image and the twibbon
|
595 |
+
image = Image.open(image_path)
|
596 |
+
twibbon = Image.open(twibbon_path)
|
597 |
+
|
598 |
+
# Get the sizes of both images
|
599 |
+
image_width, image_height = image.size
|
600 |
+
twibbon_width, twibbon_height = twibbon.size
|
601 |
+
|
602 |
+
# Resize the original image to fit inside the twibbon (optional: resize by aspect ratio)
|
603 |
+
aspect_ratio = image_width / image_height
|
604 |
+
if twibbon_width / twibbon_height > aspect_ratio:
|
605 |
+
new_width = twibbon_width
|
606 |
+
new_height = int(new_width / aspect_ratio)
|
607 |
+
else:
|
608 |
+
new_height = twibbon_height
|
609 |
+
new_width = int(new_height * aspect_ratio)
|
610 |
+
|
611 |
+
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
612 |
+
|
613 |
+
# Center the image within the twibbon
|
614 |
+
x_offset = (twibbon_width - new_width) // 2
|
615 |
+
y_offset = (twibbon_height - new_height) // 2
|
616 |
+
combined_image = Image.new('RGBA', (twibbon_width, twibbon_height))
|
617 |
+
combined_image.paste(image, (x_offset, y_offset))
|
618 |
+
combined_image.paste(twibbon, (0, 0), mask=twibbon) # Twibbon is pasted over the image
|
619 |
+
|
620 |
+
# Save the result
|
621 |
+
combined_image.save(output_path)
|
622 |
+
return combined_image
|
623 |
+
|
624 |
+
def process_twibbon(image, twibbon):
|
625 |
+
output_path = "output_image.png" # Output sementara
|
626 |
+
combined_image = add_twibbon(image.name, twibbon.name, output_path)
|
627 |
+
return combined_image
|
628 |
+
|
629 |
+
def remove_background(image_path, method="none"):
|
630 |
+
image = Image.open(image_path)
|
631 |
+
|
632 |
+
if method == "none":
|
633 |
+
return image # Return the original image without any background removal
|
634 |
+
elif method == "rembg":
|
635 |
+
image = remove_background_rembg(image_path)
|
636 |
+
elif method == "bria":
|
637 |
+
image = remove_background_bria(image_path)
|
638 |
+
|
639 |
+
return image # Default return in case no valid method is chosen
|
640 |
|
641 |
with gr.Blocks(theme="NoCrypt/miku@1.2.2") as iface:
|
642 |
gr.Markdown("# π¨ Creative Image Suite: Generate, Modify, and Enhance Your Visuals")
|
|
|
708 |
num_workers = gr.Slider(minimum=1, maximum=16, step=1, label="Number of Workers", value=5)
|
709 |
|
710 |
with gr.Row():
|
711 |
+
bg_method = gr.Radio(choices=["bria", "rembg", None], label="Background Removal Method", value="bria")
|
712 |
bg_choice = gr.Radio(choices=["transparent", "white", "custom"], label="Background Choice", value="white")
|
713 |
custom_color = gr.ColorPicker(label="Custom Background Color", value="#ffffff", visible=False)
|
714 |
|