mac9087 commited on
Commit
7a2efdb
·
verified ·
1 Parent(s): 31ca086

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -15
app.py CHANGED
@@ -19,7 +19,7 @@ from transformers import pipeline, AutoImageProcessor, AutoModelForDepthEstimati
19
  from scipy.ndimage import gaussian_filter
20
  from scipy import interpolate
21
  import cv2
22
- from backgroundremover.bg import remove
23
 
24
  app = Flask(__name__)
25
  CORS(app)
@@ -86,20 +86,25 @@ def allowed_file(filename):
86
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
87
 
88
  def remove_background(image_path):
89
- with open(image_path, "rb") as img_file:
90
- img_data = img_file.read()
91
- result = remove(img_data, alpha_matting=True, alpha_matting_foreground_threshold=240, alpha_matting_background_threshold=10)
92
- img = Image.open(io.BytesIO(result)).convert("RGBA")
93
-
94
- # Check if image is fully transparent (no object)
95
- img_array = np.array(img)
96
- if np.all(img_array[:, :, 3] == 0):
97
- return None
98
-
99
- # Create black background
100
- black_bg = Image.new("RGB", img.size, (0, 0, 0))
101
- black_bg.paste(img, (0, 0), img)
102
- return black_bg
 
 
 
 
 
103
 
104
  def preprocess_image(image_path):
105
  # Remove background and add black background
 
19
  from scipy.ndimage import gaussian_filter
20
  from scipy import interpolate
21
  import cv2
22
+ from rembg import remove
23
 
24
  app = Flask(__name__)
25
  CORS(app)
 
86
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
87
 
88
  def remove_background(image_path):
89
+ try:
90
+ with open(image_path, "rb") as img_file:
91
+ img_data = img_file.read()
92
+ result = remove(img_data)
93
+ img = Image.open(io.BytesIO(result)).convert("RGBA")
94
+
95
+ # Check if image is fully transparent (no object)
96
+ img_array = np.array(img)
97
+ if np.all(img_array[:, :, 3] == 0):
98
+ print(f"Warning: Image {image_path} is fully transparent or no object detected")
99
+ return None
100
+
101
+ # Create black background
102
+ black_bg = Image.new("RGB", img.size, (0, 0, 0))
103
+ black_bg.paste(img, (0, 0), img)
104
+ return black_bg
105
+ except Exception as e:
106
+ print(f"Error in remove_background for {image_path}: {str(e)}")
107
+ raise
108
 
109
  def preprocess_image(image_path):
110
  # Remove background and add black background