kfahn commited on
Commit
924f38c
·
verified ·
1 Parent(s): fe2c880

Update app.py

Browse files

try to remove background again

Files changed (1) hide show
  1. app.py +9 -6
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
- # Find columns that are NOT the background color
101
- mask = np.any(img_no_header != bg_color, axis=(0, 2)) # True for non-bg pixels
 
 
102
 
103
- # Find leftmost and rightmost non-bg columns
104
- left_crop = np.argmax(mask) # First non-bg column
105
- right_crop = width - np.argmax(mask[::-1]) # Last non-bg column
 
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))