Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (6)
19 unmodified lines2021222324252627205 unmodified lines23323423523623723823924024124226 unmodified lines26927027127227327419 unmodified linesFor tasks of **reboot** from a new codex session:1. Read doc/v0/PRD.md, doc/v0/Plan.md, doc/v0/Progress.md for baseline implementation2. Read doc/v1/PRD.md, doc/v1/Plan.md, doc/v1/Progress.md for edge refinement (v1)3. Assume this is a continuation of an existing project.4. Summarize your understanding of the current state and propose the next concrete step without writing code yet.## Project Overview205 unmodified lines| Flag | Values | Default | Description ||------|--------|---------|-------------|| `--finger-index` | auto, index, middle, ring, pinky | **index** | Which finger to measure and use for orientation || `--edge-method` | auto, contour, sobel, compare | auto | Edge detection method || `--sobel-threshold` | float | 15.0 | Minimum gradient magnitude || `--sobel-kernel-size` | 3, 5, 7 | 3 | Sobel kernel size || `--no-subpixel` | flag | False | Disable sub-pixel refinement |### v1 Auto Mode Behavior26 unmodified lines---## Important Technical Details### What This Measures19 unmodified lines202122232425262728205 unmodified lines23423523623723823924024124224324424526 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932019 unmodified linesFor tasks of **reboot** from a new codex session:1. Read doc/v0/PRD.md, doc/v0/Plan.md, doc/v0/Progress.md for baseline implementation2. Read doc/v1/PRD.md, doc/v1/Plan.md, doc/v1/Progress.md for edge refinement (v1)3. Read doc/v4/PRD.md, doc/v4/Plan.md, doc/v4/Progress.md for SAM 2.1 integration (card + hand)4. Assume this is a continuation of an existing project.5. Summarize your understanding of the current state and propose the next concrete step without writing code yet.## Project Overview205 unmodified lines| Flag | Values | Default | Description ||------|--------|---------|-------------|| `--finger-index` | auto, index, middle, ring, pinky | **index** | Which finger to measure and use for orientation || `--edge-method` | auto, contour, sobel, mask, compare | **mask** | Edge detection method (see v4 below) || `--sobel-threshold` | float | 15.0 | Minimum gradient magnitude || `--sobel-kernel-size` | 3, 5, 7 | 3 | Sobel kernel size || `--no-subpixel` | flag | False | Disable sub-pixel refinement || `--card-method` | classic, sam | classic | Card detection backend (v4). CLI default is `classic` to avoid surprise SAM weight downloads; web demo forces `sam`. || `--hand-mask` | synthetic, sam | **sam** | Hand mask source (v4). `synthetic` is the MediaPipe landmark convex hull. |### v1 Auto Mode Behavior26 unmodified lines---## v4 Architecture (SAM 2.1 Segmentation)v4 replaces the two fragile detection stages in v0/v1 with Meta's Segment Anything 2.1 (Hiera Small, Apache 2.0, ~150 MB). Both SAM calls are prompt-based so CPU inference stays under ~2 s total per image.### What's new in v4- **SAM-based card detection** — `src/sam_card_detection.py::detect_credit_card_sam_prompt()`. Seeds sampled outside the hand mask; each seed fires a positive prompt + negative prompts at every other seed; candidate masks are filtered by rectangularity (≥0.90), aspect ratio (1.586 ± 15%), and area bounds. ~14× faster than the original AMG grid path (which has been removed).- **SAM-based hand mask** — `src/sam_hand_segmentation.py::segment_hand_sam()`. Single positive prompt at the palm center (mean of MediaPipe landmarks 0, 5, 9, 13, 17). Replaces the old MediaPipe convex-hull polygon, which was a loose bounding shape — not a mask. Kept available under `hand_data["mask_synthetic"]` for debug.- **`mask` edge method** — new default. Measures finger width directly from the SAM mask boundary with no Sobel search. `sobel` is retained as a pure-Sobel path; when explicitly selected it now anchors its per-row search on the SAM boundary (±N pixels) instead of scanning the entire ROI.- **Shared SAM backend** (`src/sam_backend.py`) — single `Sam2Model` + `Sam2Processor` singleton shared by card + hand. Tries the local HF cache first (`local_files_only=True`) to avoid HEAD-request retry storms.- **Pipeline ordering** — hand mask runs first, its complement is used to seed card detection. This is cheap because SAM hand segmentation is ~0.5 s.### v4 module additions| Module | Purpose ||--------|---------|| `src/sam_backend.py` | Shared Sam2Model/Sam2Processor singleton || `src/sam_card_detection.py` | Prompt-based SAM card detection + seed helper || `src/sam_hand_segmentation.py` | Prompt-based SAM hand segmentation |### v4 debug additions- SAM card mask and SAM hand mask are blended onto the final debug PNG by `src/visualization.py` so the user can see what was actually measured.- `script/validate_sam_card.py` and `script/compare_hand_sam.py` are offline validation/comparison harnesses for the two SAM stages.### v4 defaults| Component | CLI default | Web demo ||---|---|---|| `--card-method` | `classic` (avoids surprise 150 MB download) | `sam` (hard-coded) || `--hand-mask` | `sam` | `sam` (hard-coded) || `--edge-method` | `mask` | `mask` (hard-coded) |### Ring / pinky handlingFor outer fingers the ROI is shrunk and rotation is centered on the proximal phalanx rather than the finger midpoint. `mask_only` measurements (i.e., the `mask` edge method) drop invalid rows and hard-fail if too few valid rows remain, rather than silently returning a low-confidence number.### Environment flags- `RING_DISABLE_SUPABASE=1` — opt out of Supabase persistence for local dev runs (the web demo otherwise persists each measurement off the request thread).---## Important Technical Details### What This Measures
19 unmodified lines2021222324252627205 unmodified lines23323423523623723823924024124226 unmodified lines26927027127227327419 unmodified linesFor tasks of **reboot** from a new codex session:1. Read doc/v0/PRD.md, doc/v0/Plan.md, doc/v0/Progress.md for baseline implementation2. Read doc/v1/PRD.md, doc/v1/Plan.md, doc/v1/Progress.md for edge refinement (v1)3. Assume this is a continuation of an existing project.4. Summarize your understanding of the current state and propose the next concrete step without writing code yet.## Project Overview205 unmodified lines| Flag | Values | Default | Description ||------|--------|---------|-------------|| `--finger-index` | auto, index, middle, ring, pinky | **index** | Which finger to measure and use for orientation || `--edge-method` | auto, contour, sobel, compare | auto | Edge detection method || `--sobel-threshold` | float | 15.0 | Minimum gradient magnitude || `--sobel-kernel-size` | 3, 5, 7 | 3 | Sobel kernel size || `--no-subpixel` | flag | False | Disable sub-pixel refinement |### v1 Auto Mode Behavior26 unmodified lines---## Important Technical Details### What This Measures19 unmodified lines202122232425262728205 unmodified lines23423523623723823924024124224324424526 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932019 unmodified linesFor tasks of **reboot** from a new codex session:1. Read doc/v0/PRD.md, doc/v0/Plan.md, doc/v0/Progress.md for baseline implementation2. Read doc/v1/PRD.md, doc/v1/Plan.md, doc/v1/Progress.md for edge refinement (v1)3. Read doc/v4/PRD.md, doc/v4/Plan.md, doc/v4/Progress.md for SAM 2.1 integration (card + hand)4. Assume this is a continuation of an existing project.5. Summarize your understanding of the current state and propose the next concrete step without writing code yet.## Project Overview205 unmodified lines| Flag | Values | Default | Description ||------|--------|---------|-------------|| `--finger-index` | auto, index, middle, ring, pinky | **index** | Which finger to measure and use for orientation || `--edge-method` | auto, contour, sobel, mask, compare | **mask** | Edge detection method (see v4 below) || `--sobel-threshold` | float | 15.0 | Minimum gradient magnitude || `--sobel-kernel-size` | 3, 5, 7 | 3 | Sobel kernel size || `--no-subpixel` | flag | False | Disable sub-pixel refinement || `--card-method` | classic, sam | classic | Card detection backend (v4). CLI default is `classic` to avoid surprise SAM weight downloads; web demo forces `sam`. || `--hand-mask` | synthetic, sam | **sam** | Hand mask source (v4). `synthetic` is the MediaPipe landmark convex hull. |### v1 Auto Mode Behavior26 unmodified lines---## v4 Architecture (SAM 2.1 Segmentation)v4 replaces the two fragile detection stages in v0/v1 with Meta's Segment Anything 2.1 (Hiera Small, Apache 2.0, ~150 MB). Both SAM calls are prompt-based so CPU inference stays under ~2 s total per image.### What's new in v4- **SAM-based card detection** — `src/sam_card_detection.py::detect_credit_card_sam_prompt()`. Seeds sampled outside the hand mask; each seed fires a positive prompt + negative prompts at every other seed; candidate masks are filtered by rectangularity (≥0.90), aspect ratio (1.586 ± 15%), and area bounds. ~14× faster than the original AMG grid path (which has been removed).- **SAM-based hand mask** — `src/sam_hand_segmentation.py::segment_hand_sam()`. Single positive prompt at the palm center (mean of MediaPipe landmarks 0, 5, 9, 13, 17). Replaces the old MediaPipe convex-hull polygon, which was a loose bounding shape — not a mask. Kept available under `hand_data["mask_synthetic"]` for debug.- **`mask` edge method** — new default. Measures finger width directly from the SAM mask boundary with no Sobel search. `sobel` is retained as a pure-Sobel path; when explicitly selected it now anchors its per-row search on the SAM boundary (±N pixels) instead of scanning the entire ROI.- **Shared SAM backend** (`src/sam_backend.py`) — single `Sam2Model` + `Sam2Processor` singleton shared by card + hand. Tries the local HF cache first (`local_files_only=True`) to avoid HEAD-request retry storms.- **Pipeline ordering** — hand mask runs first, its complement is used to seed card detection. This is cheap because SAM hand segmentation is ~0.5 s.### v4 module additions| Module | Purpose ||--------|---------|| `src/sam_backend.py` | Shared Sam2Model/Sam2Processor singleton || `src/sam_card_detection.py` | Prompt-based SAM card detection + seed helper || `src/sam_hand_segmentation.py` | Prompt-based SAM hand segmentation |### v4 debug additions- SAM card mask and SAM hand mask are blended onto the final debug PNG by `src/visualization.py` so the user can see what was actually measured.- `script/validate_sam_card.py` and `script/compare_hand_sam.py` are offline validation/comparison harnesses for the two SAM stages.### v4 defaults| Component | CLI default | Web demo ||---|---|---|| `--card-method` | `classic` (avoids surprise 150 MB download) | `sam` (hard-coded) || `--hand-mask` | `sam` | `sam` (hard-coded) || `--edge-method` | `mask` | `mask` (hard-coded) |### Ring / pinky handlingFor outer fingers the ROI is shrunk and rotation is centered on the proximal phalanx rather than the finger midpoint. `mask_only` measurements (i.e., the `mask` edge method) drop invalid rows and hard-fail if too few valid rows remain, rather than silently returning a low-confidence number.### Environment flags- `RING_DISABLE_SUPABASE=1` — opt out of Supabase persistence for local dev runs (the web demo otherwise persists each measurement off the request thread).---## Important Technical Details### What This Measures
1522 unmodified lines1523152415251526152715281529153015311532153315341535153615371538153915401522 unmodified linesvalid_rows = edge_data["valid_rows"]x_min, y_min, x_max, y_max = roi_bounds# ROI box (transform corners to canonical)roi_corners = np.array([[x_min, y_min], [x_max, y_min],[x_max, y_max], [x_min, y_max],], dtype=np.float64)if inv_mat is not None:roi_hom = np.hstack([roi_corners, np.ones((4, 1))]).Troi_can = (inv_mat @ roi_hom).T.astype(np.int32).reshape((-1, 1, 2))else:roi_can = roi_corners.astype(np.int32).reshape((-1, 1, 2))cv2.polylines(vis, [roi_can], isClosed=True, color=color, thickness=1, lineType=cv2.LINE_AA)# Edge dots and width measurement linesvalid_count = int(np.sum(valid_rows))line_spacing = max(1, valid_count // 20)1522 unmodified lines1523152415251526152715281522 unmodified linesvalid_rows = edge_data["valid_rows"]x_min, y_min, x_max, y_max = roi_bounds# Edge dots and width measurement linesvalid_count = int(np.sum(valid_rows))line_spacing = max(1, valid_count // 20)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341"""Experiment: isolate the cause of the 'staircase' edges on our SAM 2.1 hand mask.
Runs five configurations of SAM 2.1 Hiera Small against a single sample image,seeded by the MediaPipe palm center. All five variants feed the *same* pixelprompts to the *same* model; only the inference input resolution and themask-upscale strategy differ.
Configurations:
A baseline 1024-long-side hard-mask + INTER_NEAREST upscale (current) B lin_hard 1024-long-side hard-mask + INTER_LINEAR + rethresh C soft 1024-long-side raw logits -> bilinear -> threshold full-res D native_nn native hard-mask + INTER_NEAREST (no upscale needed) E native_sft native raw logits -> bilinear -> threshold
For each variant the script saves: - full-resolution binary mask PNG - hand overlay with yellow mask + green palm prompt dot - 600x600 fingertip crop centered on the middle-finger tip (landmark 12) so the staircase vs smooth comparison is visible at a glance
It also prints a small table: - perimeter (px) cv2.arcLength of the largest contour - iso ratio perimeter / sqrt(area) -- higher = more jagged - rel. to baseline (%) iso ratio relative to config A
Usage: python script/experiment_sam_mask_quality.py \\ --input input/sample-04-12/card_2.jpg \\ --output-dir output/sam_mask_quality"""from __future__ import annotations
import argparseimport sysimport timefrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple
import cv2import numpy as np
# Add repo root so we can import src.*sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from src.finger_segmentation import segment_handfrom src.sam_backend import get_sam2from src.sam_hand_segmentation import palm_center_from_landmarks
# ----------------------------------------------------------------------------# SAM inference variants# ----------------------------------------------------------------------------
def _run_sam( image_bgr: np.ndarray, palm_xy: Tuple[int, int], inference_long_side: Optional[int], upscale_mode: str,) -> Tuple[np.ndarray, float, float]: """Run SAM 2.1 with controlled inference resolution and upscale path.
Args: image_bgr: Full-resolution BGR image (canonical orientation). palm_xy: (x, y) pixel coords of palm center in the full-res image. inference_long_side: If set, downscale so long-side equals this value. If None, feed native resolution. upscale_mode: One of: - "nearest_hard": post_process_masks -> INTER_NEAREST to full res. - "linear_hard": post_process_masks -> INTER_LINEAR -> re-threshold. - "soft": raw pred_masks (256x256) -> bilinear to full res -> threshold at 0.0.
Returns: (mask_full: bool HxW, iou_score: float, infer_seconds: float) """ import torch import torch.nn.functional as F from PIL import Image as PILImage
h_full, w_full = image_bgr.shape[:2] long_side = max(h_full, w_full)
if inference_long_side is None or long_side <= inference_long_side: scaled_bgr = image_bgr scale_back = 1.0 else: s = inference_long_side / long_side new_w = int(round(w_full * s)) new_h = int(round(h_full * s)) scaled_bgr = cv2.resize(image_bgr, (new_w, new_h), interpolation=cv2.INTER_AREA) scale_back = 1.0 / s
scaled_rgb = cv2.cvtColor(scaled_bgr, cv2.COLOR_BGR2RGB) pil = PILImage.fromarray(scaled_rgb)
scale_down = 1.0 / scale_back palm_scaled = [ int(round(palm_xy[0] * scale_down)), int(round(palm_xy[1] * scale_down)), ]
model, processor = get_sam2()
t0 = time.time() inputs = processor( images=pil, input_points=[[[palm_scaled]]], input_labels=[[[1]]], return_tensors="pt", ) with torch.inference_mode(): outputs = model(**inputs, multimask_output=True)
pred_masks = outputs.pred_masks.cpu() # (1, 1, num_cands, H_low, W_low) iou_scores = outputs.iou_scores.cpu().numpy()[0, 0] best_idx = int(np.argmax(iou_scores)) best_score = float(iou_scores[best_idx])
if upscale_mode == "soft": logits = pred_masks[0, 0, best_idx].to(torch.float32) # (H_low, W_low) logits_4d = logits.unsqueeze(0).unsqueeze(0) upsampled = F.interpolate( logits_4d, size=(h_full, w_full), mode="bilinear", align_corners=False, )[0, 0].numpy() mask_full = upsampled > 0.0 else: masks_scaled = processor.post_process_masks( outputs.pred_masks.cpu(), inputs["original_sizes"], mask_threshold=0.0, )[0][0] mask_scaled = masks_scaled[best_idx].numpy().astype(np.uint8) # scaled-res
if mask_scaled.shape != (h_full, w_full): if upscale_mode == "nearest_hard": interp = cv2.INTER_NEAREST elif upscale_mode == "linear_hard": interp = cv2.INTER_LINEAR else: raise ValueError(f"unknown upscale_mode: {upscale_mode}") resized = cv2.resize(mask_scaled, (w_full, h_full), interpolation=interp) if upscale_mode == "linear_hard": mask_full = resized >= 1 # rethreshold after linear interp else: mask_full = resized.astype(bool) else: mask_full = mask_scaled.astype(bool)
return mask_full, best_score, time.time() - t0
# ----------------------------------------------------------------------------# Metrics + visualization helpers# ----------------------------------------------------------------------------
def _roughness_metrics(mask: np.ndarray) -> Dict[str, float]: """Perimeter + isoperimetric ratio of the largest contour.""" mask_u8 = (mask.astype(np.uint8)) * 255 contours, _ = cv2.findContours(mask_u8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if not contours: return {"perimeter_px": 0.0, "area_px": 0.0, "iso_ratio": float("nan")} largest = max(contours, key=cv2.contourArea) perim = float(cv2.arcLength(largest, closed=True)) area = float(cv2.contourArea(largest)) iso = perim / (np.sqrt(area) + 1e-9) return {"perimeter_px": perim, "area_px": area, "iso_ratio": iso}
def _save_overlay( path: Path, image_bgr: np.ndarray, mask: np.ndarray, palm_xy: Tuple[int, int], label: str,) -> None: overlay = image_bgr.copy() tint = np.zeros_like(overlay) tint[mask] = (0, 255, 255) overlay = cv2.addWeighted(overlay, 1.0, tint, 0.35, 0)
contours, _ = cv2.findContours( (mask.astype(np.uint8)) * 255, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE ) cv2.drawContours(overlay, contours, -1, (0, 255, 255), 2, cv2.LINE_AA)
cv2.circle(overlay, palm_xy, 18, (0, 255, 0), -1) cv2.circle(overlay, palm_xy, 18, (0, 0, 0), 3)
cv2.putText(overlay, label, (30, 60), cv2.FONT_HERSHEY_SIMPLEX, 1.1, (255, 255, 255), 5, cv2.LINE_AA) cv2.putText(overlay, label, (30, 60), cv2.FONT_HERSHEY_SIMPLEX, 1.1, (0, 255, 255), 2, cv2.LINE_AA) cv2.imwrite(str(path), overlay)
def _save_fingertip_crop( path: Path, image_bgr: np.ndarray, mask: np.ndarray, center_xy: Tuple[int, int], crop_half: int = 300, label: str = "",) -> None: h, w = image_bgr.shape[:2] cx, cy = center_xy x0 = max(0, cx - crop_half) y0 = max(0, cy - crop_half) x1 = min(w, cx + crop_half) y1 = min(h, cy + crop_half)
crop = image_bgr[y0:y1, x0:x1].copy() mask_crop = mask[y0:y1, x0:x1]
tint = np.zeros_like(crop) tint[mask_crop] = (0, 255, 255) crop = cv2.addWeighted(crop, 1.0, tint, 0.4, 0)
contours, _ = cv2.findContours( (mask_crop.astype(np.uint8)) * 255, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE ) cv2.drawContours(crop, contours, -1, (0, 255, 255), 2, cv2.LINE_AA)
if label: cv2.putText(crop, label, (15, 35), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 4, cv2.LINE_AA) cv2.putText(crop, label, (15, 35), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2, cv2.LINE_AA)
cv2.imwrite(str(path), crop)
# ----------------------------------------------------------------------------# Main# ----------------------------------------------------------------------------
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", default="input/sample-04-12/card_2.jpg") parser.add_argument("--output-dir", default="output/sam_mask_quality") args = parser.parse_args()
in_path = Path(args.input) out_dir = Path(args.output_dir) out_dir.mkdir(parents=True, exist_ok=True)
image = cv2.imread(str(in_path)) if image is None: print(f"ERROR: could not read {in_path}") return 2
print(f"Input: {in_path} ({image.shape[1]}x{image.shape[0]})")
# Get canonical image + landmarks WITHOUT running SAM. Pass a large # max_dimension so MediaPipe's internal resize does not happen and the # canonical image stays at native resolution. hand_data = segment_hand( image=image, finger="middle", max_dimension=3000, debug_dir=None, use_sam_mask=False, ) if hand_data is None: print("ERROR: hand detection failed") return 2
canonical = hand_data["canonical_image"] landmarks = hand_data["landmarks"] # (21, 2) in canonical px coords palm_xy = palm_center_from_landmarks(landmarks) middle_tip_xy = (int(round(landmarks[12, 0])), int(round(landmarks[12, 1])))
ch, cw = canonical.shape[:2] print(f"Canonical: {cw}x{ch} palm=({palm_xy[0]},{palm_xy[1]}) " f"middle_tip=({middle_tip_xy[0]},{middle_tip_xy[1]})")
# Save canonical reference image cv2.imwrite(str(out_dir / "00_canonical.png"), canonical)
variants = [ ("A_baseline_1024_nn", 1024, "nearest_hard"), ("B_1024_linear_hard", 1024, "linear_hard"), ("C_1024_soft", 1024, "soft"), ("D_native_nn", None, "nearest_hard"), ("E_native_soft", None, "soft"), ]
results = [] for name, long_side, mode in variants: print(f"\n=== {name} long_side={long_side} mode={mode} ===") mask, score, secs = _run_sam(canonical, palm_xy, long_side, mode) m = _roughness_metrics(mask) print(f" iou={score:.3f} time={secs:.2f}s " f"perim={m['perimeter_px']:.0f}px iso={m['iso_ratio']:.3f}")
cv2.imwrite(str(out_dir / f"{name}_mask.png"), (mask.astype(np.uint8)) * 255) _save_overlay( out_dir / f"{name}_overlay.png", canonical, mask, palm_xy, label=f"{name} iou={score:.2f}", ) _save_fingertip_crop( out_dir / f"{name}_fingertip.png", canonical, mask, middle_tip_xy, crop_half=300, label=name, )
results.append((name, score, secs, m["perimeter_px"], m["iso_ratio"]))
# Summary table print("\n") print("=" * 78) print(f"{'variant':<22}{'iou':>8}{'time(s)':>10}" f"{'perim(px)':>14}{'iso':>10}{'vs A (%)':>12}") print("-" * 78) iso_base = results[0][4] for name, score, secs, perim, iso in results: rel = (iso / iso_base - 1.0) * 100.0 if iso_base else float("nan") print(f"{name:<22}{score:>8.3f}{secs:>10.2f}" f"{perim:>14.0f}{iso:>10.3f}{rel:>11.1f}%") print("=" * 78)
# Side-by-side fingertip comparison crops = [cv2.imread(str(out_dir / f"{name}_fingertip.png")) for name, *_ in results] if all(c is not None for c in crops): panel = np.hstack(crops) cv2.imwrite(str(out_dir / "fingertip_comparison.png"), panel) print(f"\nFingertip comparison strip: {out_dir / 'fingertip_comparison.png'}")
print(f"\nAll outputs saved to: {out_dir}/") return 0
if __name__ == "__main__": raise SystemExit(main())1159 unmodified lines11601161116211631164116511661167116852 unmodified lines12211222122312241225122612271159 unmodified linesp2 = (zone_pt - perp_direction * roi_half_width).astype(int)cv2.line(vis, tuple(p1), tuple(p2), Color.ORANGE, 2, cv2.LINE_AA)# 3. Draw ROI boundarycv2.rectangle(vis, (x_min, y_min), (x_max, y_max), Color.CYAN, 2)# 4. Draw detected edgesline_spacing = max(1, int(np.sum(valid_rows)) // 25) # Show ~25 linescount = 052 unmodified lines"Legend:"," Yellow line = Finger axis"," Orange lines = Ring zone"," Cyan box = ROI"," Blue dots = Left edges"," Magenta dots = Right edges"," Green lines = Width measurements"1159 unmodified lines11601161116211631164116552 unmodified lines1218121912201221122212231159 unmodified linesp2 = (zone_pt - perp_direction * roi_half_width).astype(int)cv2.line(vis, tuple(p1), tuple(p2), Color.ORANGE, 2, cv2.LINE_AA)# 4. Draw detected edgesline_spacing = max(1, int(np.sum(valid_rows)) // 25) # Show ~25 linescount = 052 unmodified lines"Legend:"," Yellow line = Finger axis"," Orange lines = Ring zone"," Blue dots = Left edges"," Magenta dots = Right edges"," Green lines = Width measurements"
58 unmodified lines59606162636424 unmodified lines899091929394959697989910010110210310410510610710810911011111211311458 unmodified linesBool mask of the same shape as `image_bgr[:2]`, or None on failure."""import torchfrom PIL import Image as PILImageh_full, w_full = image_bgr.shape[:2]24 unmodified lineswith torch.inference_mode():outputs = model(**inputs, multimask_output=True)masks = processor.post_process_masks(outputs.pred_masks.cpu(),inputs["original_sizes"],mask_threshold=0.0,)[0][0] # (num_candidates, H_scaled, W_scaled)scores = outputs.iou_scores.cpu().numpy()[0, 0]best_idx = int(np.argmax(scores))mask_scaled = masks[best_idx].numpy().astype(bool)best_score = float(scores[best_idx])infer_time = time.time() - t0# Upscale back to original resolutionif mask_scaled.shape != (h_full, w_full):mask_full = cv2.resize(mask_scaled.astype(np.uint8),(w_full, h_full),interpolation=cv2.INTER_NEAREST,).astype(bool)else:mask_full = mask_scaledprint(f" SAM hand mask: score={best_score:.3f} time={infer_time:.1f}s "58 unmodified lines5960616263646524 unmodified lines9091929394959697989910010110210310410510610710810911011111211311458 unmodified linesBool mask of the same shape as `image_bgr[:2]`, or None on failure."""import torchimport torch.nn.functional as Ffrom PIL import Image as PILImageh_full, w_full = image_bgr.shape[:2]24 unmodified lineswith torch.inference_mode():outputs = model(**inputs, multimask_output=True)# Use the raw 256x256 logits and bilinearly upsample them to the full# resolution before thresholding. Going through post_process_masks +# cv2.INTER_NEAREST binarizes at the scaled resolution and then blows# the hard mask up ~4x, which produces visible staircase edges on the# finger boundaries (see script/experiment_sam_mask_quality.py).pred_masks = outputs.pred_masks.cpu() # (1, 1, num_cands, H_low, W_low)scores = outputs.iou_scores.cpu().numpy()[0, 0]best_idx = int(np.argmax(scores))best_score = float(scores[best_idx])logits_best = pred_masks[0, 0, best_idx].to(torch.float32)upsampled = F.interpolate(logits_best.unsqueeze(0).unsqueeze(0),size=(h_full, w_full),mode="bilinear",align_corners=False,)[0, 0].numpy()mask_full = upsampled > 0.0infer_time = time.time() - t0print(f" SAM hand mask: score={best_score:.3f} time={infer_time:.1f}s "
AGENTS.md+49-3
CLAUDE.md+49-3
measure_finger.py-12
script/experiment_sam_mask_quality.pyAdded+341
src/debug_observer.py-4
src/sam_hand_segmentation.py+16-16