kfahn commited on
Commit
fe2c880
·
verified ·
1 Parent(s): 62bdbcb

Update app.py

Browse files

try to remove background again

Files changed (1) hide show
  1. app.py +16 -16
app.py CHANGED
@@ -8,6 +8,7 @@ import nest_asyncio
8
  #import matplotlib
9
  from playwright.async_api import async_playwright
10
  from PIL import Image
 
11
  import subprocess
12
  import json
13
  from rapidfuzz import process
@@ -84,25 +85,24 @@ async def capture_screenshot(image_type: str):
84
 
85
  def crop_based_on_bg(image_path: str, bg_color=(59, 59, 59)):
86
  img = Image.open(image_path).convert("RGB")
87
- pixels = img.load()
88
 
89
  # Define fixed crop for top header
90
  top_crop = 50
91
- width, height = img.size
92
-
93
- # Find leftmost and rightmost non-background pixels
94
- left_crop, right_crop = 0, width
95
- for x in range(width):
96
- column = [pixels[x, y] for y in range(top_crop, height)]
97
- if any(pixel != bg_color for pixel in column):
98
- left_crop = x
99
- break
100
-
101
- for x in range(width - 1, -1, -1):
102
- column = [pixels[x, y] for y in range(top_crop, height)]
103
- if any(pixel != bg_color for pixel in column):
104
- right_crop = x
105
- break
106
 
107
  # Crop and save
108
  cropped_img = img.crop((left_crop, top_crop, right_crop, height))
 
8
  #import matplotlib
9
  from playwright.async_api import async_playwright
10
  from PIL import Image
11
+ import numpy as np
12
  import subprocess
13
  import json
14
  from rapidfuzz import process
 
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
 
90
  # Define fixed crop for top header
91
  top_crop = 50
92
+ #width, height = img.size
93
+
94
+ # Get height & width
95
+ height, width, _ = img_array.shape
96
+
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))