Spaces:
Sleeping
Sleeping
Update app.py
Browse filestry to remove background again
app.py
CHANGED
|
@@ -83,7 +83,7 @@ async def capture_screenshot(image_type: str):
|
|
| 83 |
await browser.close()
|
| 84 |
print("Screenshot saved!")
|
| 85 |
|
| 86 |
-
def crop_based_on_bg(image_path: str, bg_color=(59, 59, 59)):
|
| 87 |
img = Image.open(image_path).convert("RGB")
|
| 88 |
img_array = np.array(img)
|
| 89 |
|
|
@@ -97,12 +97,15 @@ def crop_based_on_bg(image_path: str, bg_color=(59, 59, 59)):
|
|
| 97 |
# Extract the portion of the image below the fixed header
|
| 98 |
img_no_header = img_array[top_crop:, :, :]
|
| 99 |
|
| 100 |
-
#
|
| 101 |
-
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
# Find leftmost and rightmost non-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
| 106 |
|
| 107 |
# Crop and save
|
| 108 |
cropped_img = img.crop((left_crop, top_crop, right_crop, height))
|
|
|
|
| 83 |
await browser.close()
|
| 84 |
print("Screenshot saved!")
|
| 85 |
|
| 86 |
+
def crop_based_on_bg(image_path: str, bg_color=(59, 59, 59), tolerance=10):
|
| 87 |
img = Image.open(image_path).convert("RGB")
|
| 88 |
img_array = np.array(img)
|
| 89 |
|
|
|
|
| 97 |
# Extract the portion of the image below the fixed header
|
| 98 |
img_no_header = img_array[top_crop:, :, :]
|
| 99 |
|
| 100 |
+
# Compute a mask for pixels that are NOT within the background tolerance
|
| 101 |
+
lower_bound = np.array(bg_color) - tolerance
|
| 102 |
+
upper_bound = np.array(bg_color) + tolerance
|
| 103 |
+
mask = np.any((img_no_header < lower_bound) | (img_no_header > upper_bound), axis=2)
|
| 104 |
|
| 105 |
+
# Find leftmost and rightmost non-background pixels
|
| 106 |
+
col_sums = mask.sum(axis=0)
|
| 107 |
+
left_crop = np.argmax(col_sums > 0) # First column with content
|
| 108 |
+
right_crop = width - np.argmax(col_sums[::-1] > 0) # Last column with content
|
| 109 |
|
| 110 |
# Crop and save
|
| 111 |
cropped_img = img.crop((left_crop, top_crop, right_crop, height))
|