Spaces:
Sleeping
Sleeping
border color filter
Browse files
a.jpg
ADDED
![]() |
app.py
CHANGED
@@ -9,9 +9,37 @@ import gradio as gr
|
|
9 |
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
|
10 |
from transformers import pipeline
|
11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
def resize_and_crop_image(image_path, target_size=(1080, 1080), crop_mode='center'):
|
|
|
13 |
with Image.open(image_path) as img:
|
14 |
width, height = img.size
|
|
|
15 |
|
16 |
# Calculate the scaling factor
|
17 |
scaling_factor = max(target_size[0] / width, target_size[1] / height)
|
@@ -19,6 +47,7 @@ def resize_and_crop_image(image_path, target_size=(1080, 1080), crop_mode='cente
|
|
19 |
# Resize the image with high-quality resampling
|
20 |
new_size = (int(width * scaling_factor), int(height * scaling_factor))
|
21 |
resized_img = img.resize(new_size, Image.LANCZOS)
|
|
|
22 |
|
23 |
if crop_mode == 'center':
|
24 |
left = (resized_img.width - target_size[0]) / 2
|
@@ -41,10 +70,12 @@ def resize_and_crop_image(image_path, target_size=(1080, 1080), crop_mode='cente
|
|
41 |
|
42 |
# Crop the image
|
43 |
cropped_img = resized_img.crop((left, top, right, bottom))
|
|
|
44 |
|
45 |
return cropped_img
|
46 |
|
47 |
def remove_background_rembg(input_path):
|
|
|
48 |
with open(input_path, 'rb') as i:
|
49 |
input_image = i.read()
|
50 |
output_image = remove(input_image)
|
@@ -52,28 +83,54 @@ def remove_background_rembg(input_path):
|
|
52 |
return img
|
53 |
|
54 |
def remove_background_bria(input_path):
|
|
|
55 |
pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True)
|
56 |
pillow_image = pipe(input_path) # applies mask on input and returns a pillow image
|
57 |
return pillow_image
|
58 |
|
59 |
-
def process_single_image(image_path, output_folder, crop_mode,
|
60 |
filename = os.path.basename(image_path)
|
61 |
try:
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
else:
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
# Save both versions of the image (with and without watermark)
|
79 |
images_paths = []
|
@@ -99,17 +156,17 @@ def process_single_image(image_path, output_folder, crop_mode, remove_bg, bg_met
|
|
99 |
new_image_with_watermark.save(output_path_with_watermark, format='PNG')
|
100 |
images_paths.append(output_path_with_watermark)
|
101 |
|
102 |
-
|
103 |
-
|
104 |
-
os.remove(temp_image_path)
|
105 |
|
|
|
106 |
return images_paths
|
107 |
|
108 |
except Exception as e:
|
109 |
print(f"Error processing {filename}: {e}")
|
110 |
return None
|
111 |
|
112 |
-
def process_images(zip_file, crop_mode='center',
|
113 |
start_time = time.time()
|
114 |
|
115 |
# Create a temporary directory
|
@@ -123,21 +180,29 @@ def process_images(zip_file, crop_mode='center', remove_bg='yes', bg_method='rem
|
|
123 |
os.makedirs(output_folder)
|
124 |
|
125 |
# Extract the zip file
|
126 |
-
|
127 |
-
|
|
|
|
|
|
|
|
|
128 |
|
129 |
processed_images = []
|
130 |
image_files = [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
|
131 |
total_images = len(image_files)
|
|
|
132 |
|
133 |
# Process images using ThreadPoolExecutor for I/O-bound tasks and ProcessPoolExecutor for CPU-bound tasks
|
134 |
with ThreadPoolExecutor(max_workers=num_workers) as thread_executor:
|
135 |
with ProcessPoolExecutor(max_workers=num_workers) as process_executor:
|
136 |
-
future_to_image = {thread_executor.submit(process_single_image, image_path, output_folder, crop_mode,
|
137 |
for idx, future in enumerate(future_to_image):
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
141 |
# Update progress
|
142 |
progress((idx + 1) / total_images, f"{idx + 1}/{total_images} images processed")
|
143 |
|
@@ -152,22 +217,23 @@ def process_images(zip_file, crop_mode='center', remove_bg='yes', bg_method='rem
|
|
152 |
|
153 |
end_time = time.time()
|
154 |
processing_time = end_time - start_time
|
|
|
155 |
|
156 |
# Return the images, the zip file path, and processing time
|
157 |
return processed_images, output_zip_path, processing_time
|
158 |
|
159 |
-
def gradio_interface(zip_file, crop_mode,
|
160 |
progress = gr.Progress() # Initialize progress
|
161 |
watermark_path = watermark.name if watermark else None
|
162 |
-
return process_images(zip_file.name, crop_mode,
|
163 |
|
164 |
-
def show_bg_choice(
|
165 |
-
if
|
166 |
return gr.update(visible=True)
|
167 |
return gr.update(visible=False)
|
168 |
|
169 |
-
def
|
170 |
-
if
|
171 |
return gr.update(visible=True)
|
172 |
return gr.update(visible=False)
|
173 |
|
@@ -182,29 +248,28 @@ with gr.Blocks() as iface:
|
|
182 |
|
183 |
with gr.Row():
|
184 |
crop_mode = gr.Radio(choices=["center", "top", "bottom", "left", "right"], label="Crop Mode", value="center")
|
185 |
-
remove_bg = gr.Radio(choices=["yes", "no"], label="Remove Background", value="yes")
|
186 |
|
187 |
output_format = gr.Radio(choices=["PNG", "JPG"], label="Output Format", value="PNG")
|
188 |
num_workers = gr.Slider(minimum=1, maximum=16, step=1, label="Number of Workers", value=2)
|
189 |
|
190 |
with gr.Row():
|
191 |
bg_method = gr.Radio(choices=["bria", "rembg"], label="Background Removal Method", value="bria", visible=True)
|
192 |
-
bg_choice = gr.Radio(choices=["transparent", "white"], label="Background Choice", value="transparent", visible=True)
|
|
|
193 |
|
194 |
-
|
195 |
-
|
196 |
-
output_format.change(show_bg_choice, inputs=[remove_bg, output_format], outputs=bg_choice)
|
197 |
|
198 |
gallery = gr.Gallery(label="Processed Images")
|
199 |
output_zip = gr.File(label="Download Processed Images as ZIP")
|
200 |
processing_time = gr.Textbox(label="Processing Time (seconds)")
|
201 |
|
202 |
-
def process(zip_file, crop_mode,
|
203 |
-
processed_images, zip_path, time_taken = gradio_interface(zip_file, crop_mode,
|
204 |
return processed_images, zip_path, f"{time_taken:.2f} seconds"
|
205 |
|
206 |
process_button = gr.Button("Process Images")
|
207 |
-
process_button.click(process, inputs=[zip_file, crop_mode,
|
208 |
|
209 |
# Launch the interface
|
210 |
iface.launch()
|
|
|
9 |
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
|
10 |
from transformers import pipeline
|
11 |
|
12 |
+
def colors_within_tolerance(color1, color2, tolerance):
|
13 |
+
return all(abs(c1 - c2) <= tolerance for c1, c2 in zip(color1, color2))
|
14 |
+
|
15 |
+
def check_border_colors(image_path, tolerance):
|
16 |
+
# Open the image
|
17 |
+
image = Image.open(image_path)
|
18 |
+
pixels = image.load()
|
19 |
+
|
20 |
+
width, height = image.size
|
21 |
+
|
22 |
+
# Get the color of the first pixel on the left and right borders
|
23 |
+
left_border_color = pixels[0, 0]
|
24 |
+
right_border_color = pixels[width - 1, 0]
|
25 |
+
|
26 |
+
# Check the left border
|
27 |
+
for y in range(height):
|
28 |
+
if not colors_within_tolerance(pixels[0, y], left_border_color, tolerance):
|
29 |
+
return False
|
30 |
+
|
31 |
+
# Check the right border
|
32 |
+
for y in range(height):
|
33 |
+
if not colors_within_tolerance(pixels[width - 1, y], right_border_color, tolerance):
|
34 |
+
return False
|
35 |
+
|
36 |
+
return True
|
37 |
+
|
38 |
def resize_and_crop_image(image_path, target_size=(1080, 1080), crop_mode='center'):
|
39 |
+
print(f"Resizing and cropping image: {image_path}")
|
40 |
with Image.open(image_path) as img:
|
41 |
width, height = img.size
|
42 |
+
print(f"Original image size: {width}x{height}")
|
43 |
|
44 |
# Calculate the scaling factor
|
45 |
scaling_factor = max(target_size[0] / width, target_size[1] / height)
|
|
|
47 |
# Resize the image with high-quality resampling
|
48 |
new_size = (int(width * scaling_factor), int(height * scaling_factor))
|
49 |
resized_img = img.resize(new_size, Image.LANCZOS)
|
50 |
+
print(f"Resized image size: {new_size}")
|
51 |
|
52 |
if crop_mode == 'center':
|
53 |
left = (resized_img.width - target_size[0]) / 2
|
|
|
70 |
|
71 |
# Crop the image
|
72 |
cropped_img = resized_img.crop((left, top, right, bottom))
|
73 |
+
print(f"Cropped image size: {cropped_img.size}")
|
74 |
|
75 |
return cropped_img
|
76 |
|
77 |
def remove_background_rembg(input_path):
|
78 |
+
print(f"Removing background using rembg for image: {input_path}")
|
79 |
with open(input_path, 'rb') as i:
|
80 |
input_image = i.read()
|
81 |
output_image = remove(input_image)
|
|
|
83 |
return img
|
84 |
|
85 |
def remove_background_bria(input_path):
|
86 |
+
print(f"Removing background using bria for image: {input_path}")
|
87 |
pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True)
|
88 |
pillow_image = pipe(input_path) # applies mask on input and returns a pillow image
|
89 |
return pillow_image
|
90 |
|
91 |
+
def process_single_image(image_path, output_folder, crop_mode, bg_method, output_format, bg_choice, custom_color, watermark_path=None):
|
92 |
filename = os.path.basename(image_path)
|
93 |
try:
|
94 |
+
print(f"Processing image: {filename}")
|
95 |
+
if bg_method == 'rembg':
|
96 |
+
# Remove background using rembg
|
97 |
+
image_with_no_bg = remove_background_rembg(image_path)
|
98 |
+
elif bg_method == 'bria':
|
99 |
+
# Remove background using bria
|
100 |
+
image_with_no_bg = remove_background_bria(image_path)
|
101 |
+
|
102 |
+
temp_image_path = os.path.join(output_folder, f"temp_{filename}")
|
103 |
+
image_with_no_bg.save(temp_image_path, format='PNG')
|
104 |
+
|
105 |
+
# Check border colors and categorize
|
106 |
+
if check_border_colors(temp_image_path, tolerance=50):
|
107 |
+
print(f"Border colors are the same for image: {filename}")
|
108 |
+
# Create a new 1080x1080 canvas
|
109 |
+
if bg_choice == 'transparent':
|
110 |
+
new_image = Image.new("RGBA", (1080, 1080), (255, 255, 255, 0))
|
111 |
+
else:
|
112 |
+
new_image = Image.new("RGBA", (1080, 1080), custom_color)
|
113 |
+
|
114 |
+
# Scale image to fit inside the canvas without stretching
|
115 |
+
width, height = image_with_no_bg.size
|
116 |
+
scaling_factor = min(1080 / width, 1080 / height)
|
117 |
+
new_size = (int(width * scaling_factor), int(height * scaling_factor))
|
118 |
+
resized_img = image_with_no_bg.resize(new_size, Image.LANCZOS)
|
119 |
+
print(f"Resized image size: {new_size}")
|
120 |
+
new_image.paste(resized_img, ((1080 - resized_img.width) // 2, (1080 - resized_img.height) // 2))
|
121 |
else:
|
122 |
+
print(f"Border colors are different for image: {filename}")
|
123 |
+
new_image = resize_and_crop_image(temp_image_path, crop_mode=crop_mode)
|
124 |
+
|
125 |
+
# Change background color if needed
|
126 |
+
if bg_choice == 'white':
|
127 |
+
new_image = new_image.convert("RGBA")
|
128 |
+
white_bg = Image.new("RGBA", new_image.size, "WHITE")
|
129 |
+
new_image = Image.alpha_composite(white_bg, new_image)
|
130 |
+
elif bg_choice == 'custom':
|
131 |
+
new_image = new_image.convert("RGBA")
|
132 |
+
custom_bg = Image.new("RGBA", new_image.size, custom_color)
|
133 |
+
new_image = Image.alpha_composite(custom_bg, new_image)
|
134 |
|
135 |
# Save both versions of the image (with and without watermark)
|
136 |
images_paths = []
|
|
|
156 |
new_image_with_watermark.save(output_path_with_watermark, format='PNG')
|
157 |
images_paths.append(output_path_with_watermark)
|
158 |
|
159 |
+
# Remove the temporary file
|
160 |
+
os.remove(temp_image_path)
|
|
|
161 |
|
162 |
+
print(f"Processed image paths: {images_paths}")
|
163 |
return images_paths
|
164 |
|
165 |
except Exception as e:
|
166 |
print(f"Error processing {filename}: {e}")
|
167 |
return None
|
168 |
|
169 |
+
def process_images(zip_file, crop_mode='center', bg_method='rembg', watermark_path=None, output_format='PNG', bg_choice='transparent', custom_color="#ffffff", num_workers=4, progress=gr.Progress()):
|
170 |
start_time = time.time()
|
171 |
|
172 |
# Create a temporary directory
|
|
|
180 |
os.makedirs(output_folder)
|
181 |
|
182 |
# Extract the zip file
|
183 |
+
try:
|
184 |
+
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
|
185 |
+
zip_ref.extractall(input_folder)
|
186 |
+
except zipfile.BadZipFile as e:
|
187 |
+
print(f"Error extracting zip file: {e}")
|
188 |
+
return [], None, 0
|
189 |
|
190 |
processed_images = []
|
191 |
image_files = [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]
|
192 |
total_images = len(image_files)
|
193 |
+
print(f"Total images to process: {total_images}")
|
194 |
|
195 |
# Process images using ThreadPoolExecutor for I/O-bound tasks and ProcessPoolExecutor for CPU-bound tasks
|
196 |
with ThreadPoolExecutor(max_workers=num_workers) as thread_executor:
|
197 |
with ProcessPoolExecutor(max_workers=num_workers) as process_executor:
|
198 |
+
future_to_image = {thread_executor.submit(process_single_image, image_path, output_folder, crop_mode, bg_method, output_format, bg_choice, custom_color, watermark_path): image_path for image_path in image_files}
|
199 |
for idx, future in enumerate(future_to_image):
|
200 |
+
try:
|
201 |
+
result = future.result()
|
202 |
+
if result:
|
203 |
+
processed_images.extend(result)
|
204 |
+
except Exception as e:
|
205 |
+
print(f"Error processing image {future_to_image[future]}: {e}")
|
206 |
# Update progress
|
207 |
progress((idx + 1) / total_images, f"{idx + 1}/{total_images} images processed")
|
208 |
|
|
|
217 |
|
218 |
end_time = time.time()
|
219 |
processing_time = end_time - start_time
|
220 |
+
print(f"Processing time: {processing_time} seconds")
|
221 |
|
222 |
# Return the images, the zip file path, and processing time
|
223 |
return processed_images, output_zip_path, processing_time
|
224 |
|
225 |
+
def gradio_interface(zip_file, crop_mode, bg_method, watermark, output_format, bg_choice, custom_color, num_workers):
|
226 |
progress = gr.Progress() # Initialize progress
|
227 |
watermark_path = watermark.name if watermark else None
|
228 |
+
return process_images(zip_file.name, crop_mode, bg_method, watermark_path, output_format, bg_choice, custom_color, num_workers, progress)
|
229 |
|
230 |
+
def show_bg_choice(output_format):
|
231 |
+
if output_format == 'PNG':
|
232 |
return gr.update(visible=True)
|
233 |
return gr.update(visible=False)
|
234 |
|
235 |
+
def show_color_picker(bg_choice):
|
236 |
+
if bg_choice == 'custom':
|
237 |
return gr.update(visible=True)
|
238 |
return gr.update(visible=False)
|
239 |
|
|
|
248 |
|
249 |
with gr.Row():
|
250 |
crop_mode = gr.Radio(choices=["center", "top", "bottom", "left", "right"], label="Crop Mode", value="center")
|
|
|
251 |
|
252 |
output_format = gr.Radio(choices=["PNG", "JPG"], label="Output Format", value="PNG")
|
253 |
num_workers = gr.Slider(minimum=1, maximum=16, step=1, label="Number of Workers", value=2)
|
254 |
|
255 |
with gr.Row():
|
256 |
bg_method = gr.Radio(choices=["bria", "rembg"], label="Background Removal Method", value="bria", visible=True)
|
257 |
+
bg_choice = gr.Radio(choices=["transparent", "white", "custom"], label="Background Choice", value="transparent", visible=True)
|
258 |
+
custom_color = gr.ColorPicker(label="Custom Background Color", value="#ffffff", visible=False)
|
259 |
|
260 |
+
bg_choice.change(show_color_picker, inputs=bg_choice, outputs=custom_color)
|
261 |
+
output_format.change(show_bg_choice, inputs=output_format, outputs=bg_choice)
|
|
|
262 |
|
263 |
gallery = gr.Gallery(label="Processed Images")
|
264 |
output_zip = gr.File(label="Download Processed Images as ZIP")
|
265 |
processing_time = gr.Textbox(label="Processing Time (seconds)")
|
266 |
|
267 |
+
def process(zip_file, crop_mode, bg_method, watermark, output_format, bg_choice, custom_color, num_workers):
|
268 |
+
processed_images, zip_path, time_taken = gradio_interface(zip_file, crop_mode, bg_method, watermark, output_format, bg_choice, custom_color, num_workers)
|
269 |
return processed_images, zip_path, f"{time_taken:.2f} seconds"
|
270 |
|
271 |
process_button = gr.Button("Process Images")
|
272 |
+
process_button.click(process, inputs=[zip_file, crop_mode, bg_method, watermark, output_format, bg_choice, custom_color, num_workers], outputs=[gallery, output_zip, processing_time])
|
273 |
|
274 |
# Launch the interface
|
275 |
iface.launch()
|
b.jpg
ADDED
![]() |
pixel_border.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
def colors_within_tolerance(color1, color2, tolerance):
|
6 |
+
return all(abs(c1 - c2) <= tolerance for c1, c2 in zip(color1, color2))
|
7 |
+
|
8 |
+
def check_border_colors(image_path, tolerance):
|
9 |
+
# Open the image
|
10 |
+
image = Image.open(image_path)
|
11 |
+
pixels = image.load()
|
12 |
+
|
13 |
+
width, height = image.size
|
14 |
+
|
15 |
+
# Get the color of the first pixel on the left and right borders
|
16 |
+
left_border_color = pixels[0, 0]
|
17 |
+
right_border_color = pixels[width - 1, 0]
|
18 |
+
|
19 |
+
# Check the left border
|
20 |
+
for y in range(height):
|
21 |
+
if not colors_within_tolerance(pixels[0, y], left_border_color, tolerance):
|
22 |
+
return False
|
23 |
+
|
24 |
+
# Check the right border
|
25 |
+
for y in range(height):
|
26 |
+
if not colors_within_tolerance(pixels[width - 1, y], right_border_color, tolerance):
|
27 |
+
return False
|
28 |
+
|
29 |
+
return True
|
30 |
+
|
31 |
+
def process_images(input_folder, output_folder_same, output_folder_different, tolerance):
|
32 |
+
# Ensure output directories exist
|
33 |
+
os.makedirs(output_folder_same, exist_ok=True)
|
34 |
+
os.makedirs(output_folder_different, exist_ok=True)
|
35 |
+
|
36 |
+
for filename in os.listdir(input_folder):
|
37 |
+
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
|
38 |
+
image_path = os.path.join(input_folder, filename)
|
39 |
+
if check_border_colors(image_path, tolerance):
|
40 |
+
shutil.copy(image_path, os.path.join(output_folder_same, filename))
|
41 |
+
else:
|
42 |
+
shutil.copy(image_path, os.path.join(output_folder_different, filename))
|
43 |
+
|
44 |
+
# Example usage
|
45 |
+
input_folder = 'D:\Ardha\Kerja\AISensum\ROX\Task 1'
|
46 |
+
output_folder_same = 'D:\Ardha\Kerja\AISensum\ROX\Task 1\warna_sama'
|
47 |
+
output_folder_different = 'D:\Ardha\Kerja\AISensum\ROX\Task 1\warna_berbeda'
|
48 |
+
tolerance = 50 # Adjust the tolerance value as needed
|
49 |
+
|
50 |
+
process_images(input_folder, output_folder_same, output_folder_different, tolerance)
|