mlbench123 commited on
Commit
9506b4e
·
verified ·
1 Parent(s): b579854

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -105
app.py CHANGED
@@ -171,76 +171,6 @@ def get_birefnet():
171
  logger.info("BiRefNet model loaded successfully")
172
  return birefnet
173
 
174
- # def detect_paper_contour(image: np.ndarray) -> Tuple[np.ndarray, float]:
175
- # """
176
- # Detect paper in the image using contour detection as fallback
177
- # Returns the paper contour and estimated scaling factor
178
- # """
179
- # logger.info("Using contour-based paper detection")
180
-
181
- # # Convert to grayscale
182
- # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) if len(image.shape) == 3 else image
183
-
184
- # # Apply bilateral filter to reduce noise while preserving edges
185
- # filtered = cv2.bilateralFilter(gray, 9, 75, 75)
186
-
187
- # # Apply adaptive threshold
188
- # thresh = cv2.adaptiveThreshold(filtered, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
189
- # cv2.THRESH_BINARY, 11, 2)
190
-
191
- # # Edge detection with multiple thresholds
192
- # edges1 = cv2.Canny(filtered, 50, 150)
193
- # edges2 = cv2.Canny(filtered, 30, 100)
194
- # edges = cv2.bitwise_or(edges1, edges2)
195
-
196
- # # Morphological operations to connect broken edges
197
- # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
198
- # edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
199
-
200
- # # Find contours
201
- # contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
202
-
203
- # # Filter contours by area and aspect ratio to find paper-like rectangles
204
- # paper_contours = []
205
- # image_area = image.shape[0] * image.shape[1]
206
- # min_area = image_area * 0.20 # At least 15% of image
207
- # max_area = image_area * 0.85 # At most 95% of image
208
-
209
- # for contour in contours:
210
- # area = cv2.contourArea(contour)
211
- # if min_area < area < max_area:
212
- # # Approximate contour to polygon
213
- # epsilon = 0.015 * cv2.arcLength(contour, True)
214
- # approx = cv2.approxPolyDP(contour, epsilon, True)
215
-
216
- # # Check if it's roughly rectangular (4 corners) or close to it
217
- # if len(approx) >= 4:
218
- # # Calculate bounding rectangle
219
- # rect = cv2.boundingRect(approx)
220
- # w, h = rect[2], rect[3]
221
- # aspect_ratio = w / h if h > 0 else 0
222
-
223
- # # Check if aspect ratio matches common paper ratios
224
- # # A4: 1.414, A3: 1.414, US Letter: 1.294
225
- # if 1.3 < aspect_ratio < 1.5: # More lenient tolerance
226
- # # Check if contour area is close to bounding rect area (rectangularity)
227
- # rect_area = w * h
228
- # if rect_area > 0:
229
- # extent = area / rect_area
230
- # if extent > 0.85: # At least 70% rectangular
231
- # paper_contours.append((contour, area, aspect_ratio, extent))
232
-
233
- # if not paper_contours:
234
- # logger.error("No paper-like contours found")
235
- # raise ReferenceBoxNotDetectedError("Could not detect paper in the image using contour detection")
236
-
237
- # # Select the best paper contour based on area and rectangularity
238
- # paper_contours.sort(key=lambda x: (x[1] * x[3]), reverse=True) # Sort by area * extent
239
- # best_contour = paper_contours[0][0]
240
-
241
- # logger.info(f"Paper detected using contours: area={paper_contours[0][1]}, aspect_ratio={paper_contours[0][2]:.2f}")
242
-
243
- # return best_contour, 0.0 # Return 0.0 as placeholder scaling factor
244
  def detect_paper_contour(image: np.ndarray, output_unit: str = "mm") -> Tuple[np.ndarray, float]:
245
  """
246
  Detect paper in the image using contour detection as fallback
@@ -492,38 +422,6 @@ def remove_bg(image: np.ndarray) -> np.ndarray:
492
  logger.error(f"Error in BiRefNet background removal: {e}")
493
  raise
494
 
495
- # def exclude_paper_area(mask: np.ndarray, paper_contour: np.ndarray, expansion_factor: float = 1.2) -> np.ndarray:
496
- # """
497
- # Remove paper area from the mask to focus only on objects
498
- # """
499
- # # Create paper mask with slight expansion to ensure complete removal
500
- # paper_mask = np.zeros(mask.shape[:2], dtype=np.uint8)
501
-
502
- # # # Expand paper contour slightly
503
- # # epsilon = expansion_factor * cv2.arcLength(paper_contour, True)
504
- # # expanded_contour = cv2.approxPolyDP(paper_contour, epsilon, True)
505
-
506
- # # cv2.fillPoly(paper_mask, [expanded_contour], 255)
507
- # # Create a more aggressive inward shrinking of paper bounds
508
- # rect = cv2.boundingRect(paper_contour)
509
- # shrink_pixels = int(min(rect[2], rect[3]) * 0.05) # Shrink by 5% of smaller dimension
510
-
511
- # # Create shrunken rectangle
512
- # x, y, w, h = rect
513
- # shrunken_contour = np.array([
514
- # [[x + shrink_pixels, y + shrink_pixels]],
515
- # [[x + w - shrink_pixels, y + shrink_pixels]],
516
- # [[x + w - shrink_pixels, y + h - shrink_pixels]],
517
- # [[x + shrink_pixels, y + h - shrink_pixels]]
518
- # ])
519
-
520
- # cv2.fillPoly(paper_mask, [shrunken_contour], 255)
521
-
522
- # # Invert paper mask and apply to object mask
523
- # paper_mask_inv = cv2.bitwise_not(paper_mask)
524
- # result_mask = cv2.bitwise_and(mask, paper_mask_inv)
525
-
526
- # return result_mask
527
  def mask_paper_area_in_image(image: np.ndarray, paper_contour: np.ndarray) -> np.ndarray:
528
  """Less aggressive masking to preserve corner objects"""
529
  masked_image = image.copy()
@@ -1233,9 +1131,9 @@ if __name__ == "__main__":
1233
  inputs=[
1234
  input_image,
1235
  paper_size,
1236
- # offset_value_mm,
1237
- # offset_unit,
1238
- # enable_finger_cut,
1239
  output_options
1240
  ],
1241
  outputs=[dxf_file, output_image, outlines_image, mask_image, scale_info]
 
171
  logger.info("BiRefNet model loaded successfully")
172
  return birefnet
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  def detect_paper_contour(image: np.ndarray, output_unit: str = "mm") -> Tuple[np.ndarray, float]:
175
  """
176
  Detect paper in the image using contour detection as fallback
 
422
  logger.error(f"Error in BiRefNet background removal: {e}")
423
  raise
424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  def mask_paper_area_in_image(image: np.ndarray, paper_contour: np.ndarray) -> np.ndarray:
426
  """Less aggressive masking to preserve corner objects"""
427
  masked_image = image.copy()
 
1131
  inputs=[
1132
  input_image,
1133
  paper_size,
1134
+ 0.02,
1135
+ 'mm',
1136
+ 'Off',
1137
  output_options
1138
  ],
1139
  outputs=[dxf_file, output_image, outlines_image, mask_image, scale_info]