havan2605 commited on
Commit
8b3a882
Β·
verified Β·
1 Parent(s): b265d34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -36
app.py CHANGED
@@ -18,13 +18,18 @@ import numpy as np
18
  import torch
19
  import cv2
20
  from PIL import Image, ExifTags
21
- from scipy import ndimage
22
  import gradio as gr
23
 
24
  from transformers import Sam3Processor, Sam3Model
25
  from depth_anything_3.api import DepthAnything3
26
 
27
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
28
  HF_TOKEN = os.environ.get("HF_TOKEN") # set as a Space secret if sam3 is gated for you
29
  ARUCO_DICT = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
30
 
@@ -40,7 +45,9 @@ _depther = None
40
  def get_segmenter():
41
  global _segmenter
42
  if _segmenter is None:
43
- model = Sam3Model.from_pretrained("facebook/sam3", token=HF_TOKEN).to(DEVICE)
 
 
44
  processor = Sam3Processor.from_pretrained("facebook/sam3", token=HF_TOKEN)
45
  _segmenter = (model, processor)
46
  return _segmenter
@@ -58,10 +65,23 @@ def get_depther(model_id: str):
58
  # Pipeline stages (same logic as the standalone script)
59
  # --------------------------------------------------------------------------
60
 
61
- def segment(image: Image.Image, text_prompt: str, score_threshold: float = 0.5) -> np.ndarray:
 
 
 
 
 
 
 
 
 
 
62
  model, processor = get_segmenter()
63
- inputs = processor(images=image, text=text_prompt, return_tensors="pt").to(DEVICE)
64
- with torch.no_grad():
 
 
 
65
  outputs = model(**inputs)
66
 
67
  results = processor.post_process_instance_segmentation(
@@ -69,26 +89,35 @@ def segment(image: Image.Image, text_prompt: str, score_threshold: float = 0.5)
69
  threshold=score_threshold,
70
  mask_threshold=0.5,
71
  target_sizes=inputs.get("original_sizes").tolist(),
72
- )[0]
73
 
74
- masks = results["masks"]
75
- scores = results["scores"]
 
 
76
 
77
- if len(masks) == 0:
78
- raise gr.Error(f"No object found matching '{text_prompt}' above the confidence "
79
- f"threshold ({score_threshold}). Try a more specific or different phrase.")
 
 
80
 
81
- best_idx = int(torch.argmax(scores))
82
- mask = masks[best_idx]
83
- if hasattr(mask, "cpu"):
84
- mask = mask.cpu().numpy()
85
- return np.asarray(mask).astype(bool)
 
86
 
87
 
88
  def erode_mask(mask: np.ndarray, pixels: int = 3) -> np.ndarray:
89
  if pixels <= 0:
90
  return mask
91
- eroded = ndimage.binary_erosion(mask, iterations=pixels)
 
 
 
 
92
  return eroded if eroded.sum() > 20 else mask
93
 
94
 
@@ -136,8 +165,9 @@ def mask_overlay(image: Image.Image, masks: list) -> Image.Image:
136
  """Tints each object's mask a distinct color (cycling through
137
  OBJECT_COLORS if there are more objects than colors) for a quick
138
  visual sanity-check of what got segmented."""
139
- arr = np.array(image).astype(np.float32)
140
- overlay = arr.copy()
 
141
  for i, mask in enumerate(masks):
142
  color = np.array(OBJECT_COLORS[i % len(OBJECT_COLORS)])
143
  overlay[mask] = overlay[mask] * 0.4 + color * 0.6
@@ -187,6 +217,23 @@ def intrinsics_from_exif(image: Image.Image):
187
  return None
188
 
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  # --------------------------------------------------------------------------
191
  # Addition 3: automatic scale calibration via an ArUco marker of known
192
  # physical size, instead of requiring the user to type in a measured
@@ -271,17 +318,17 @@ def run_pipeline(files, objects_text, depth_model_id, erosion_px,
271
 
272
  primary_image = images[0]
273
 
274
- # Segment each object independently. A bad prompt for one object
275
- # shouldn't discard valid results for the others, so failures are
276
- # collected and reported rather than raised immediately.
 
277
  masks, valid_names, seg_warnings = [], [], []
278
- for name in object_names:
279
- try:
280
- mask = erode_mask(segment(primary_image, name), erosion_px)
281
- masks.append(mask)
282
- valid_names.append(name)
283
- except gr.Error as e:
284
- seg_warnings.append(f"'{name}': {e}")
285
 
286
  for w in seg_warnings:
287
  gr.Warning(f"Skipped {w}")
@@ -340,8 +387,10 @@ def run_pipeline(files, objects_text, depth_model_id, erosion_px,
340
 
341
  # Addition 2: prefer EXIF-derived intrinsics over DA3's estimated ones
342
  # when available and requested β€” a known camera beats a network guess.
343
- # Intrinsics are NOT optional (3D back-projection needs them), so if DA3
344
- # didn't return them, EXIF becomes required rather than just preferred.
 
 
345
  intrinsics = prediction.intrinsics[0] if prediction.intrinsics is not None else None
346
  intrinsics_source = "DA3 (estimated)"
347
  if use_exif_intrinsics or intrinsics is None:
@@ -350,11 +399,20 @@ def run_pipeline(files, objects_text, depth_model_id, erosion_px,
350
  intrinsics = exif_intrinsics
351
  intrinsics_source = "EXIF (35mm-equivalent focal length)"
352
  elif intrinsics is None:
353
- raise gr.Error(
354
- "Camera intrinsics were unavailable from both DA3 and the image's EXIF data, "
355
- "so 3D positions can't be computed. Try a photo with intact EXIF metadata "
356
- "(avoid re-saving/re-compressing it, which often strips EXIF), or check the "
357
- "Space logs for [diag] lines to see what DA3 actually returned."
 
 
 
 
 
 
 
 
 
358
  )
359
  else:
360
  gr.Warning("No usable focal-length EXIF tag found on the primary image β€” "
 
18
  import torch
19
  import cv2
20
  from PIL import Image, ExifTags
 
21
  import gradio as gr
22
 
23
  from transformers import Sam3Processor, Sam3Model
24
  from depth_anything_3.api import DepthAnything3
25
 
26
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
27
+ # Half precision on CUDA gives a large SAM3 speed/memory win with negligible
28
+ # accuracy impact for this pipeline (mask thresholds are coarse-grained);
29
+ # CPU stays fp32 since there's no benefit there. Depth Anything 3 already
30
+ # does its own internal mixed-precision autocast (see DepthAnything3.forward
31
+ # in depth_anything_3/api.py), so it doesn't need this treatment here.
32
+ SAM3_DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
33
  HF_TOKEN = os.environ.get("HF_TOKEN") # set as a Space secret if sam3 is gated for you
34
  ARUCO_DICT = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
35
 
 
45
  def get_segmenter():
46
  global _segmenter
47
  if _segmenter is None:
48
+ model = Sam3Model.from_pretrained(
49
+ "facebook/sam3", token=HF_TOKEN, torch_dtype=SAM3_DTYPE
50
+ ).to(DEVICE)
51
  processor = Sam3Processor.from_pretrained("facebook/sam3", token=HF_TOKEN)
52
  _segmenter = (model, processor)
53
  return _segmenter
 
65
  # Pipeline stages (same logic as the standalone script)
66
  # --------------------------------------------------------------------------
67
 
68
+ def segment_batch(image: Image.Image, text_prompts: list, score_threshold: float = 0.5) -> list:
69
+ """Segments every text prompt against the same primary image in a single
70
+ batched SAM3 forward pass, instead of one full forward pass (image
71
+ encoder included) per object as before. The image is simply repeated
72
+ across the batch dimension so `Sam3Processor`/`Sam3Model` treat it as
73
+ `len(text_prompts)` independent (image, text) pairs, one call instead of
74
+ N sequential Python-level calls.
75
+
76
+ Returns a list of (mask_or_None, error_message_or_None) tuples, one per
77
+ entry in `text_prompts`, in the same order.
78
+ """
79
  model, processor = get_segmenter()
80
+ images = [image] * len(text_prompts)
81
+ # dtype must match the (possibly fp16) model weights, or the forward
82
+ # pass will fail with a dtype-mismatch error on `pixel_values`.
83
+ inputs = processor(images=images, text=text_prompts, return_tensors="pt").to(DEVICE, dtype=SAM3_DTYPE)
84
+ with torch.inference_mode():
85
  outputs = model(**inputs)
86
 
87
  results = processor.post_process_instance_segmentation(
 
89
  threshold=score_threshold,
90
  mask_threshold=0.5,
91
  target_sizes=inputs.get("original_sizes").tolist(),
92
+ )
93
 
94
+ per_prompt = []
95
+ for text_prompt, result in zip(text_prompts, results):
96
+ masks = result["masks"]
97
+ scores = result["scores"]
98
 
99
+ if len(masks) == 0:
100
+ per_prompt.append((None,
101
+ f"No object found matching '{text_prompt}' above the confidence "
102
+ f"threshold ({score_threshold}). Try a more specific or different phrase."))
103
+ continue
104
 
105
+ best_idx = int(torch.argmax(scores))
106
+ mask = masks[best_idx]
107
+ if hasattr(mask, "cpu"):
108
+ mask = mask.cpu().numpy()
109
+ per_prompt.append((np.asarray(mask).astype(bool), None))
110
+ return per_prompt
111
 
112
 
113
  def erode_mask(mask: np.ndarray, pixels: int = 3) -> np.ndarray:
114
  if pixels <= 0:
115
  return mask
116
+ # cv2.erode is substantially faster than scipy.ndimage.binary_erosion for
117
+ # simple binary structuring-element erosion on 2D masks. A 3x3 cross
118
+ # kernel matches scipy's default 4-connected structuring element.
119
+ kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
120
+ eroded = cv2.erode(mask.astype(np.uint8), kernel, iterations=pixels).astype(bool)
121
  return eroded if eroded.sum() > 20 else mask
122
 
123
 
 
165
  """Tints each object's mask a distinct color (cycling through
166
  OBJECT_COLORS if there are more objects than colors) for a quick
167
  visual sanity-check of what got segmented."""
168
+ # np.array(image).astype(np.float32) already allocates a fresh array, so
169
+ # no extra .copy() is needed before mutating it in place.
170
+ overlay = np.array(image).astype(np.float32)
171
  for i, mask in enumerate(masks):
172
  color = np.array(OBJECT_COLORS[i % len(OBJECT_COLORS)])
173
  overlay[mask] = overlay[mask] * 0.4 + color * 0.6
 
217
  return None
218
 
219
 
220
+ def default_intrinsics(image: Image.Image, assumed_focal_35mm: float = 26.0) -> np.ndarray:
221
+ """Last-resort fallback intrinsics for when neither DA3 nor the image's
222
+ EXIF data provide any β€” e.g. screenshots, re-compressed/re-saved
223
+ photos, or images from sources that strip metadata. Assumes a ~26mm
224
+ 35mm-equivalent focal length (typical of smartphone main cameras) and a
225
+ 36mm-wide full-frame-equivalent sensor, same approximation as
226
+ `intrinsics_from_exif`. This is a coarse guess, not a calibration β€”
227
+ resulting distances should be treated as rough estimates rather than
228
+ precise measurements, but it lets the pipeline still produce a result
229
+ instead of hard-failing."""
230
+ w, h = image.size
231
+ fx = (assumed_focal_35mm / 36.0) * w
232
+ fy = fx # assume square pixels
233
+ cx, cy = w / 2.0, h / 2.0
234
+ return np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float64)
235
+
236
+
237
  # --------------------------------------------------------------------------
238
  # Addition 3: automatic scale calibration via an ArUco marker of known
239
  # physical size, instead of requiring the user to type in a measured
 
318
 
319
  primary_image = images[0]
320
 
321
+ # Segment every object in a single batched SAM3 forward pass (one image,
322
+ # N text prompts) instead of one full forward pass per object. A bad
323
+ # prompt for one object shouldn't discard valid results for the others,
324
+ # so failures are collected and reported rather than raised immediately.
325
  masks, valid_names, seg_warnings = [], [], []
326
+ for name, (mask, err) in zip(object_names, segment_batch(primary_image, object_names)):
327
+ if err is not None:
328
+ seg_warnings.append(f"'{name}': {err}")
329
+ continue
330
+ masks.append(erode_mask(mask, erosion_px))
331
+ valid_names.append(name)
 
332
 
333
  for w in seg_warnings:
334
  gr.Warning(f"Skipped {w}")
 
387
 
388
  # Addition 2: prefer EXIF-derived intrinsics over DA3's estimated ones
389
  # when available and requested β€” a known camera beats a network guess.
390
+ # Intrinsics are required for 3D back-projection; if DA3 didn't return
391
+ # them, EXIF is tried next, and if that's also unavailable we fall back
392
+ # to a rough default assumption (see default_intrinsics()) rather than
393
+ # failing the whole request.
394
  intrinsics = prediction.intrinsics[0] if prediction.intrinsics is not None else None
395
  intrinsics_source = "DA3 (estimated)"
396
  if use_exif_intrinsics or intrinsics is None:
 
399
  intrinsics = exif_intrinsics
400
  intrinsics_source = "EXIF (35mm-equivalent focal length)"
401
  elif intrinsics is None:
402
+ # Neither DA3 nor EXIF gave us intrinsics (e.g. a screenshot or a
403
+ # re-compressed image with stripped metadata). Rather than hard-
404
+ # failing the whole pipeline, degrade gracefully to a rough
405
+ # default focal-length assumption so the user still gets a
406
+ # result, just flagged as approximate.
407
+ intrinsics = default_intrinsics(primary_image)
408
+ intrinsics_source = "default estimate (~26mm-equivalent focal length assumption)"
409
+ gr.Warning(
410
+ "Camera intrinsics were unavailable from both DA3 and the image's EXIF data "
411
+ "(e.g. no EXIF on this image). Falling back to a default focal-length "
412
+ "assumption (~26mm-equivalent, typical smartphone camera) β€” treat the "
413
+ "resulting distances as rough estimates rather than precise measurements. "
414
+ "For better accuracy, provide a photo with intact EXIF metadata (avoid "
415
+ "re-saving/re-compressing it, which often strips EXIF)."
416
  )
417
  else:
418
  gr.Warning("No usable focal-length EXIF tag found on the primary image β€” "