Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (8)
- README.md+54-62
- measure_finger.py+43
- script/analyze_calibration.pyAdded+323
- script/batch_measure.pyAdded+177
- script/deploy_hf.shAdded+21
- src/calibration.jsonAdded+10
- web_demo/app.py+8-1
- web_demo/static/app.js+2
10 unmodified lines111213141516171819202122232425262714 unmodified lines4243444546476 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413510 unmodified linesLocal computer-vision CLI tool that measures **finger outer diameter** from a single image using a **credit card** as scale reference.## What it does- Detects a credit card and computes `px/cm` scale.- Detects hand/finger with MediaPipe.- Measures finger width in the ring-wearing zone.- Supports dual edge modes:- `contour` (v0 baseline)- `sobel` (v1 refinement)- `auto` (default, Sobel with quality fallback)- `compare` (returns both method stats)- Writes JSON output and always writes a result PNG next to it.## Install```bashpython -m venv .venv14 unmodified lines# Finger selectionpython measure_finger.py --input image.jpg --output output/result.json --finger-index ring# Force methodpython measure_finger.py --input image.jpg --output output/result.json --edge-method contourpython measure_finger.py --input image.jpg --output output/result.json --edge-method sobel6 unmodified lines--edge-method sobel --sobel-threshold 15 --sobel-kernel-size 3 --no-subpixel```## CLI flags (current)- `--input` (required)- `--output` (required)- `--debug` (boolean; saves intermediate debug folders)- `--save-intermediate`- `--finger-index {auto,index,middle,ring,pinky}` (default `index`)- `--confidence-threshold` (default `0.7`)- `--edge-method {auto,contour,sobel,compare}` (default `auto`)- `--sobel-threshold` (default `15.0`)- `--sobel-kernel-size {3,5,7}` (default `3`)- `--no-subpixel`- `--skip-card-detection` (testing only)## Output JSON```json{"finger_outer_diameter_cm": 1.78,"confidence": 0.91,"scale_px_per_cm": 203.46,"quality_flags": {"card_detected": true,"finger_detected": true,"view_angle_ok": true},"fail_reason": null,"edge_method_used": "contour_fallback","method_comparison": {"contour": {"width_cm": 1.82,"width_px": 371.2,"std_dev_px": 3.8,"coefficient_variation": 0.01,"num_samples": 20,"method": "contour"},"sobel": {"width_cm": 1.78,"width_px": 362.0,"std_dev_px": 3.1,"coefficient_variation": 0.008,"num_samples": 140,"subpixel_used": true,"success_rate": 0.42,"edge_quality_score": 0.81,"method": "sobel"},"difference": {"absolute_cm": -0.04,"absolute_px": -9.2,"relative_pct": -2.2,"precision_improvement": 0.7},"recommendation": {"use_sobel": true,"reason": "quality_acceptable","preferred_method": "sobel"},"quality_comparison": {"contour_cv": 0.01,"sobel_cv": 0.008,"sobel_quality_score": 0.81,"sobel_gradient_strength": 0.82,"sobel_consistency": 0.42,"sobel_smoothness": 0.91,"sobel_symmetry": 0.95}}}```Notes:- `edge_method_used` and `method_comparison` are optional (present when relevant).- Result image path is auto-derived: `output/result.json` -> `output/result.png`.## Documentation map- Requirement docs: `doc/v{i}/PRD.md`, `doc/v{i}/Plan.md`, `doc/v{i}/Progress.md`- Algorithms index: `doc/algorithms/README.md`- Scripts: `script/README.md`- Web demo: `web_demo/README.md`10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464714 unmodified lines6263646566676869706 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612710 unmodified linesLocal computer-vision CLI tool that measures **finger outer diameter** from a single image using a **credit card** as scale reference.## Live Demo- Hugging Face Space: [https://huggingface.co/spaces/feng-x/ring-sizer](https://huggingface.co/spaces/feng-x/ring-sizer)- Anyone can try the hosted web demo directly in the browser.## What it does- Detects a credit card and computes `px/cm` scale.- Detects hand/finger with MediaPipe.- Measures finger width in the ring-wearing zone.- **Regression calibration** corrects systematic over-measurement (MAE: 0.158 → 0.060 cm).- Supports dual edge modes:- `contour` (v0 baseline)- `sobel` (v1 sub-pixel refinement)- `auto` (default, Sobel with quality fallback)- `compare` (returns both method stats)- Writes JSON output and always writes a result PNG next to it.## AccuracyValidated on 10 subjects × 3 fingers × 2 photos = 60 measurements against caliper ground truth.| Metric | Before Calibration | After Calibration ||--------|-------------------|-------------------|| MAE | 0.158 cm | **0.060 cm** || RMSE | 0.176 cm | **0.075 cm** || Max error | 0.347 cm | **0.174 cm** |Pipeline stability: card detection CV = 0.44%, shot-to-shot repeatability = 0.028 cm.See full report: [`doc/report/calibration_report.md`](doc/report/calibration_report.md)## Install```bashpython -m venv .venv14 unmodified lines# Finger selectionpython measure_finger.py --input image.jpg --output output/result.json --finger-index ring# Disable calibration (raw measurement only)python measure_finger.py --input image.jpg --output output/result.json --no-calibration# Force methodpython measure_finger.py --input image.jpg --output output/result.json --edge-method contourpython measure_finger.py --input image.jpg --output output/result.json --edge-method sobel6 unmodified lines--edge-method sobel --sobel-threshold 15 --sobel-kernel-size 3 --no-subpixel```## CLI flags| Flag | Values | Default | Description ||------|--------|---------|-------------|| `--input` | path | *(required)* | Input image (JPG/PNG) || `--output` | path | *(required)* | Output JSON path || `--debug` | flag | false | Save intermediate debug images || `--finger-index` | auto, index, middle, ring, pinky | index | Which finger to measure || `--confidence-threshold` | float | 0.7 | Minimum confidence threshold || `--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 || `--no-calibration` | flag | false | Output raw measurement only || `--skip-card-detection` | flag | false | Testing only |## Output JSON```json{"finger_outer_diameter_cm": 1.78,"confidence": 0.91,"scale_px_per_cm": 128.03,"quality_flags": {"card_detected": true,"finger_detected": true,"view_angle_ok": true},"fail_reason": null,"edge_method_used": "sobel","raw_diameter_cm": 1.92,"calibration_applied": true}```Notes:- `raw_diameter_cm` is the pre-calibration measurement (present when calibration is applied).- `edge_method_used` and `method_comparison` are optional (present when relevant).- Result image path is auto-derived: `output/result.json` → `output/result.png`.## Documentation| Path | Contents ||------|----------|| [`doc/v0/`](doc/v0/) | v0 PRD, Plan, Progress (contour baseline) || [`doc/v1/`](doc/v1/) | v1 PRD, Plan, Progress (Sobel edge refinement) || [`doc/v2/`](doc/v2/) | v2 Plan, Progress (calibration & regression) || [`doc/report/`](doc/report/) | Validation & calibration report || [`doc/algorithms/`](doc/algorithms/) | Algorithm documentation || [`script/`](script/) | Batch measurement & analysis scripts || [`web_demo/`](web_demo/) | Web demo (Flask) |
31 unmodified lines32333435363779 unmodified lines117118119120121122208 unmodified lines331332333334335336408 unmodified lines7457467477487497504 unmodified lines75575675775875976031 unmodified lines)from src.debug_observer import draw_comprehensive_edge_overlay# Type alias for finger selectionFingerIndex = Literal["auto", "index", "middle", "ring", "pinky"]79 unmodified lineshelp="Disable sub-pixel edge refinement",)# Testing/debugging optionsparser.add_argument("--skip-card-detection",208 unmodified linesview_angle_ok = scale_confidence > 0.9card_detected = True# Phase 5: Finger isolation (hand already segmented in Phase 3)h_can, w_can = image_canonical.shape[:2]finger_data = isolate_finger(hand_data, finger=finger_index, image_shape=(h_can, w_can))408 unmodified linesskip_card_detection=args.skip_card_detection,)# Save outputsave_output(result, args.output)print(f"Results saved to: {args.output}")4 unmodified linesreturn 1else:print(f"Finger diameter: {result['finger_outer_diameter_cm']} cm")print(f"Confidence: {result['confidence']}")return 031 unmodified lines3233343536373839404142434445464748495079 unmodified lines130131132133134135136137138139140141142208 unmodified lines351352353354355356357358359360361362363364365366367408 unmodified lines7767777787797807817827837847857867877887897907914 unmodified lines79679779879980080180280331 unmodified lines)from src.debug_observer import draw_comprehensive_edge_overlay# Calibration coefficients (from regression on 60 measurements)_CALIBRATION_PATH = Path(__file__).parent / "src" / "calibration.json"def _load_calibration() -> dict:"""Load calibration coefficients from JSON."""with open(_CALIBRATION_PATH) as f:return json.load(f)def apply_calibration(raw_diameter_cm: float) -> float:"""Apply linear regression calibration: actual = slope * raw + intercept."""cal = _load_calibration()return cal["slope"] * raw_diameter_cm + cal["intercept"]# Type alias for finger selectionFingerIndex = Literal["auto", "index", "middle", "ring", "pinky"]79 unmodified lineshelp="Disable sub-pixel edge refinement",)# Calibrationparser.add_argument("--no-calibration",action="store_true",help="Disable regression calibration (output raw measurement only)",)# Testing/debugging optionsparser.add_argument("--skip-card-detection",208 unmodified linesview_angle_ok = scale_confidence > 0.9card_detected = True# Reject if card is not parallel enough to cameraif not view_angle_ok:print(f"Card not parallel to camera (scale_confidence={scale_confidence:.2f}, required>0.9)")return create_output(card_detected=True,finger_detected=False,scale_px_per_cm=px_per_cm,view_angle_ok=False,fail_reason="card_not_parallel",)# Phase 5: Finger isolation (hand already segmented in Phase 3)h_can, w_can = image_canonical.shape[:2]finger_data = isolate_finger(hand_data, finger=finger_index, image_shape=(h_can, w_can))408 unmodified linesskip_card_detection=args.skip_card_detection,)# Apply calibration (post-processing)raw_diameter = result.get("finger_outer_diameter_cm")if raw_diameter is not None and not args.no_calibration:calibrated = apply_calibration(raw_diameter)result["finger_outer_diameter_cm"] = round(calibrated, 4)result["raw_diameter_cm"] = round(raw_diameter, 4)result["calibration_applied"] = Trueelse:result["calibration_applied"] = False# Save outputsave_output(result, args.output)print(f"Results saved to: {args.output}")4 unmodified linesreturn 1else:print(f"Finger diameter: {result['finger_outer_diameter_cm']} cm")if result.get("raw_diameter_cm"):print(f" (raw: {result['raw_diameter_cm']} cm, calibrated)")print(f"Confidence: {result['confidence']}")return 0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323#!/usr/bin/env python3"""Analysis & regression script for calibration dataset.
Performs:1. px/cm stability analysis2. A vs B repeatability3. Ground truth sanity check (π×diameter vs circumference)4. Scatter plot & bias analysis5. Linear regression with leave-one-person-out cross-validation"""
import jsonimport mathimport osfrom pathlib import Path
import numpy as np
# Optional: matplotlib for plots (skip gracefully if missing)try: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt HAS_PLT = Trueexcept ImportError: HAS_PLT = False print("Warning: matplotlib not available, skipping plots")
def load_results(path: str) -> list[dict]: with open(path, encoding="utf-8") as f: return json.load(f)
def section(title: str): print(f"\n{'='*60}") print(f" {title}") print(f"{'='*60}")
def analyze_scale_stability(results: list[dict]): """Phase 3a: px/cm stability across all images.""" section("1. Card Detection / px/cm Stability")
scales = {} for r in results: img = r["image"] if img not in scales and r["cv_scale_px_per_cm"]: scales[img] = r["cv_scale_px_per_cm"]
vals = list(scales.values()) mean_s = np.mean(vals) std_s = np.std(vals) cv_pct = (std_s / mean_s) * 100
print(f" Images analyzed: {len(scales)}") print(f" Mean px/cm: {mean_s:.2f}") print(f" Std px/cm: {std_s:.2f}") print(f" CV%: {cv_pct:.2f}%") print(f" Range: {min(vals):.2f} — {max(vals):.2f}") print(f" Max spread: {max(vals)-min(vals):.2f} px/cm ({(max(vals)-min(vals))/mean_s*100:.2f}%)")
# Per-image table print(f"\n {'Image':<16} {'px/cm':>8} {'Δ from mean':>12}") print(f" {'-'*38}") for img, s in sorted(scales.items()): print(f" {img:<16} {s:>8.2f} {s-mean_s:>+12.2f}")
return mean_s, std_s
def analyze_repeatability(results: list[dict]): """Phase 3b: A vs B repeatability.""" section("2. A vs B Repeatability")
# Group by (person, finger) pairs = {} for r in results: key = (r["person"], r["finger_en"]) if key not in pairs: pairs[key] = {} pairs[key][r["shot"]] = r["cv_diameter_cm"]
diffs = [] print(f" {'Person':<10} {'Finger':<8} {'Shot A':>8} {'Shot B':>8} {'Δ(B-A)':>8} {'%diff':>7}") print(f" {'-'*53}") for (person, finger), shots in sorted(pairs.items()): a = shots.get("A") b = shots.get("B") if a and b: d = b - a pct = abs(d) / ((a + b) / 2) * 100 diffs.append(abs(d)) print(f" {person:<10} {finger:<8} {a:>8.3f} {b:>8.3f} {d:>+8.3f} {pct:>6.1f}%")
if diffs: print(f"\n Mean |A-B| difference: {np.mean(diffs):.4f} cm") print(f" Max |A-B| difference: {max(diffs):.4f} cm") print(f" Std |A-B| difference: {np.std(diffs):.4f} cm") print(f" 95th percentile: {np.percentile(diffs, 95):.4f} cm")
return diffs
def check_ground_truth_sanity(results: list[dict]): """Phase 3c: Check π×diameter ≈ circumference.""" section("3. Ground Truth Sanity (π×diameter vs circumference)")
seen = set() diffs = [] print(f" {'Person':<10} {'Finger':<6} {'Diam':>6} {'Circ':>6} {'π×D':>6} {'Δ':>7} {'%err':>6}") print(f" {'-'*55}")
for r in results: key = (r["person"], r["finger_cn"]) if key in seen: continue seen.add(key)
d = r["gt_diameter_cm"] c = r["gt_circumference_cm"] if d and c: pi_d = math.pi * d diff = c - pi_d pct = diff / c * 100 diffs.append(diff) print(f" {r['person']:<10} {r['finger_cn']:<6} {d:>6.2f} {c:>6.1f} {pi_d:>6.2f} {diff:>+7.2f} {pct:>+5.1f}%")
if diffs: print(f"\n Mean (circ - π×diam): {np.mean(diffs):+.3f} cm") print(f" This is expected: circumference > π×diameter because") print(f" fingers are not perfect circles (slightly oval/flattened).")
def bias_analysis(results: list[dict]): """Phase 4a: Scatter plot and bias analysis.""" section("4. Accuracy & Bias Analysis")
valid = [r for r in results if r["cv_diameter_cm"] and r["gt_diameter_cm"]] cv = np.array([r["cv_diameter_cm"] for r in valid]) gt = np.array([r["gt_diameter_cm"] for r in valid]) errors = cv - gt pct_errors = errors / gt * 100
print(f" N = {len(valid)} measurements") print(f" Mean error (CV-GT): {np.mean(errors):+.4f} cm") print(f" Median error: {np.median(errors):+.4f} cm") print(f" Std of error: {np.std(errors):.4f} cm") print(f" Mean % error: {np.mean(pct_errors):+.1f}%") print(f" MAE (absolute): {np.mean(np.abs(errors)):.4f} cm") print(f" Max error: {np.max(np.abs(errors)):.4f} cm") print(f" RMSE: {np.sqrt(np.mean(errors**2)):.4f} cm")
# Correlation corr = np.corrcoef(cv, gt)[0, 1] print(f" Pearson r: {corr:.4f}") print(f" R²: {corr**2:.4f}")
return cv, gt, errors
def linear_regression(cv: np.ndarray, gt: np.ndarray, results: list[dict]): """Phase 4b: OLS regression + leave-one-person-out CV.""" section("5. Linear Regression Calibration")
# Fit: gt = a * cv + b A = np.vstack([cv, np.ones(len(cv))]).T (a, b), residuals, _, _ = np.linalg.lstsq(A, gt, rcond=None)
calibrated = a * cv + b cal_errors = calibrated - gt
print(f" Model: actual = {a:.4f} × measured + {b:.4f}") print(f" (i.e., slope={a:.4f}, intercept={b:.4f})") print(f"\n After calibration:") print(f" Mean error: {np.mean(cal_errors):+.4f} cm") print(f" MAE: {np.mean(np.abs(cal_errors)):.4f} cm") print(f" Max error: {np.max(np.abs(cal_errors)):.4f} cm") print(f" RMSE: {np.sqrt(np.mean(cal_errors**2)):.4f} cm")
# Leave-one-person-out cross-validation section("6. Leave-One-Person-Out Cross-Validation")
persons = sorted(set(r["person"] for r in results if r["cv_diameter_cm"] and r["gt_diameter_cm"])) all_cv_errors = [] all_cv_cal_errors = []
print(f" {'Person':<10} {'N':>3} {'a':>7} {'b':>7} {'MAE_raw':>8} {'MAE_cal':>8} {'Max_cal':>8}") print(f" {'-'*57}")
for holdout in persons: # Train on all except holdout train = [r for r in results if r["cv_diameter_cm"] and r["gt_diameter_cm"] and r["person"] != holdout] test = [r for r in results if r["cv_diameter_cm"] and r["gt_diameter_cm"] and r["person"] == holdout]
train_cv = np.array([r["cv_diameter_cm"] for r in train]) train_gt = np.array([r["gt_diameter_cm"] for r in train]) test_cv = np.array([r["cv_diameter_cm"] for r in test]) test_gt = np.array([r["gt_diameter_cm"] for r in test])
A_train = np.vstack([train_cv, np.ones(len(train_cv))]).T (a_fold, b_fold), _, _, _ = np.linalg.lstsq(A_train, train_gt, rcond=None)
test_cal = a_fold * test_cv + b_fold raw_errors = np.abs(test_cv - test_gt) cal_errors_fold = np.abs(test_cal - test_gt)
all_cv_errors.extend(raw_errors.tolist()) all_cv_cal_errors.extend(cal_errors_fold.tolist())
print(f" {holdout:<10} {len(test):>3} {a_fold:>7.4f} {b_fold:>+7.4f} " f"{np.mean(raw_errors):>8.4f} {np.mean(cal_errors_fold):>8.4f} " f"{np.max(cal_errors_fold):>8.4f}")
all_cv_errors = np.array(all_cv_errors) all_cv_cal_errors = np.array(all_cv_cal_errors)
print(f"\n Cross-validated results (all holdout predictions):") print(f" Raw MAE: {np.mean(all_cv_errors):.4f} cm") print(f" Cal MAE: {np.mean(all_cv_cal_errors):.4f} cm") print(f" Raw RMSE: {np.sqrt(np.mean(all_cv_errors**2)):.4f} cm") print(f" Cal RMSE: {np.sqrt(np.mean(all_cv_cal_errors**2)):.4f} cm") print(f" Improvement: {(1 - np.mean(all_cv_cal_errors)/np.mean(all_cv_errors))*100:.1f}% reduction in MAE")
return a, b
def generate_plots(cv: np.ndarray, gt: np.ndarray, a: float, b: float, out_dir: str): """Generate scatter plot and residual plot.""" if not HAS_PLT: return
section("7. Generating Plots")
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
# 1. Scatter: CV vs GT with regression line ax = axes[0] ax.scatter(cv, gt, alpha=0.6, s=30, label="Measurements") lim = [min(cv.min(), gt.min()) - 0.1, max(cv.max(), gt.max()) + 0.1] ax.plot(lim, lim, "k--", alpha=0.3, label="y=x (perfect)") x_fit = np.linspace(lim[0], lim[1], 100) ax.plot(x_fit, a * x_fit + b, "r-", linewidth=2, label=f"Fit: y={a:.3f}x{b:+.3f}") ax.set_xlabel("CV Measured Diameter (cm)") ax.set_ylabel("Actual Diameter (cm)") ax.set_title("CV Measured vs Actual (Caliper)") ax.legend(fontsize=8) ax.set_aspect("equal") ax.grid(True, alpha=0.3)
# 2. Error distribution ax = axes[1] errors = cv - gt cal_errors = (a * cv + b) - gt ax.hist(errors, bins=15, alpha=0.5, label=f"Raw (μ={np.mean(errors):+.3f})") ax.hist(cal_errors, bins=15, alpha=0.5, label=f"Calibrated (μ={np.mean(cal_errors):+.3f})") ax.axvline(0, color="k", linestyle="--", alpha=0.3) ax.set_xlabel("Error (cm)") ax.set_ylabel("Count") ax.set_title("Error Distribution: Before vs After Calibration") ax.legend(fontsize=8) ax.grid(True, alpha=0.3)
# 3. Residuals vs predicted ax = axes[2] calibrated = a * cv + b ax.scatter(calibrated, cal_errors, alpha=0.6, s=30) ax.axhline(0, color="k", linestyle="--", alpha=0.3) ax.set_xlabel("Calibrated Diameter (cm)") ax.set_ylabel("Residual (cm)") ax.set_title("Residuals After Calibration") ax.grid(True, alpha=0.3)
plt.tight_layout() plot_path = os.path.join(out_dir, "calibration_analysis.png") plt.savefig(plot_path, dpi=150) print(f" Saved plot: {plot_path}") plt.close()
def main(): base_dir = Path(__file__).resolve().parent.parent results_path = base_dir / "output" / "batch" / "batch_results.json" out_dir = str(base_dir / "output" / "batch")
results = load_results(str(results_path)) print(f"Loaded {len(results)} results")
# Phase 3 analyze_scale_stability(results) analyze_repeatability(results) check_ground_truth_sanity(results)
# Phase 4 cv, gt, errors = bias_analysis(results) a, b = linear_regression(cv, gt, results) generate_plots(cv, gt, a, b, out_dir)
# Summary section("SUMMARY — Calibration Coefficients") print(f" actual_diameter = {a:.6f} × measured_diameter + ({b:.6f})") print(f" slope (a) = {a:.6f}") print(f" offset (b) = {b:.6f}") print(f"\n Save these to the pipeline configuration.")
# Write coefficients to file coeff_path = os.path.join(out_dir, "calibration_coefficients.json") with open(coeff_path, "w") as f: json.dump({ "slope": round(a, 6), "intercept": round(b, 6), "description": "actual = slope * measured + intercept", "n_samples": len(cv), "dataset": "input/sample (10 people × 3 fingers × 2 shots)", }, f, indent=2) print(f" Saved coefficients: {coeff_path}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177#!/usr/bin/env python3"""Batch measurement script for calibration dataset.
Runs measure_finger.py on all sample images × 3 fingers,collects results, and writes to CSV + JSON."""
import csvimport jsonimport osimport subprocessimport sysfrom pathlib import Path
# Finger name mapping (Chinese → CLI arg)FINGER_MAP = { "食指": "index", "中指": "middle", "无名指": "ring",}
# People to exclude (no ground truth)EXCLUDE = {"谢峰", "空白"}
def run_measurement(image_path: str, finger: str, output_json: str) -> dict: """Run measure_finger.py and return parsed JSON result.""" cmd = [ sys.executable, "measure_finger.py", "--input", image_path, "--output", output_json, "--finger-index", finger, "--edge-method", "sobel", ] try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=120 ) if os.path.exists(output_json): with open(output_json) as f: return json.load(f) else: return {"fail_reason": f"no output file; stderr={proc.stderr[-200:]}"} except subprocess.TimeoutExpired: return {"fail_reason": "timeout"} except Exception as e: return {"fail_reason": str(e)}
def load_ground_truth(csv_path: str) -> list[dict]: """Load ground truth CSV.""" rows = [] with open(csv_path, encoding="utf-8-sig") as f: reader = csv.DictReader(f) for row in reader: rows.append(row) return rows
def main(): base_dir = Path(__file__).resolve().parent.parent os.chdir(base_dir)
jpg_dir = base_dir / "input" / "sample" / "jpg" csv_path = base_dir / "input" / "sample" / "finger-size.csv" out_dir = base_dir / "output" / "batch" out_dir.mkdir(parents=True, exist_ok=True)
# Load ground truth gt_rows = load_ground_truth(str(csv_path)) print(f"Loaded {len(gt_rows)} ground truth rows")
# Build name→rows lookup gt_by_name = {} for row in gt_rows: name = row["姓名"] if name not in gt_by_name: gt_by_name[name] = {} finger_cn = row["手指"] gt_by_name[name][finger_cn] = row
# Find all person images (exclude 谢峰, 空白) images = sorted([ f for f in jpg_dir.glob("*.jpg") if not any(ex in f.stem for ex in EXCLUDE) ]) print(f"Found {len(images)} images to process")
all_results = [] total = len(images) * 3 # 3 fingers per image done = 0
for img_path in images: stem = img_path.stem # e.g. "黄漫玉A" person = stem[:-1] # e.g. "黄漫玉" shot = stem[-1] # e.g. "A"
if person not in gt_by_name: print(f" SKIP {stem}: no ground truth for {person}") continue
for finger_cn, finger_en in FINGER_MAP.items(): done += 1 gt_row = gt_by_name[person].get(finger_cn) gt_diameter = float(gt_row["直径(cm)"]) if gt_row else None gt_circumference = float(gt_row["周长(cm)"]) if gt_row else None gt_ring_size = gt_row.get("指环尺寸", "") if gt_row else ""
out_json = str(out_dir / f"{stem}_{finger_en}.json") print(f"[{done}/{total}] {stem} / {finger_cn} ({finger_en})...", end=" ", flush=True)
result = run_measurement(str(img_path), finger_en, out_json)
cv_diameter = result.get("finger_outer_diameter_cm") cv_confidence = result.get("confidence") cv_scale = result.get("scale_px_per_cm") fail = result.get("fail_reason")
if cv_diameter and gt_diameter: error = cv_diameter - gt_diameter pct = error / gt_diameter * 100 print(f"CV={cv_diameter:.3f} GT={gt_diameter:.3f} Δ={error:+.3f} ({pct:+.1f}%) scale={cv_scale}") elif fail: print(f"FAILED: {fail[:80]}") else: print(f"CV={cv_diameter} (no GT)")
all_results.append({ "person": person, "shot": shot, "finger_cn": finger_cn, "finger_en": finger_en, "image": img_path.name, "gt_diameter_cm": gt_diameter, "gt_circumference_cm": gt_circumference, "gt_ring_size": gt_ring_size, "cv_diameter_cm": cv_diameter, "cv_confidence": cv_confidence, "cv_scale_px_per_cm": cv_scale, "fail_reason": fail, "edge_method": result.get("edge_method_used"), })
# Save full results JSON results_json = str(out_dir / "batch_results.json") with open(results_json, "w", encoding="utf-8") as f: json.dump(all_results, f, indent=2, ensure_ascii=False) print(f"\nSaved {len(all_results)} results to {results_json}")
# Save summary CSV results_csv = str(out_dir / "batch_results.csv") if all_results: keys = all_results[0].keys() with open(results_csv, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=keys) writer.writeheader() writer.writerows(all_results) print(f"Saved CSV to {results_csv}")
# Quick stats valid = [r for r in all_results if r["cv_diameter_cm"] and r["gt_diameter_cm"]] failed = [r for r in all_results if r["fail_reason"]] if valid: errors = [r["cv_diameter_cm"] - r["gt_diameter_cm"] for r in valid] mean_err = sum(errors) / len(errors) scales = [r["cv_scale_px_per_cm"] for r in valid if r["cv_scale_px_per_cm"]] mean_scale = sum(scales) / len(scales) if scales else 0 print(f"\n--- Quick Stats ---") print(f"Valid measurements: {len(valid)}/{len(all_results)}") print(f"Failed: {len(failed)}") print(f"Mean error (CV - GT): {mean_err:+.4f} cm") print(f"Mean scale: {mean_scale:.2f} px/cm") print(f"Scale range: {min(scales):.2f} - {max(scales):.2f} px/cm")
if __name__ == "__main__": main()123456789101112131415161718192021#!/usr/bin/env bash# Deploy current working directory to Hugging Face Spacesset -euo pipefail
REPO_ID="Feng-X/ring-sizer"IGNORE='[".venv/*", ".git/*", "__pycache__/*", "*.pyc", "output/*", "web_demo/uploads/*", "web_demo/results/*", "doc/*", ".claude/*", "input/*"]'
cd "$(dirname "$0")/.."
source .venv/bin/activate
python -c "from huggingface_hub import HfApiHfApi().upload_folder( folder_path='.', repo_id='${REPO_ID}', repo_type='space', ignore_patterns=${IGNORE},)print('Deployed to https://huggingface.co/spaces/${REPO_ID}')"12345678910{ "slope": 0.792112, "intercept": 0.250292, "description": "calibrated_diameter = slope * raw_diameter + intercept", "n_samples": 60, "dataset": "10 people x 3 fingers x 2 shots, caliper ground truth", "raw_mae_cm": 0.1578, "calibrated_mae_cm": 0.0601, "cv_mae_cm": 0.0601}18 unmodified lines1920212223242597 unmodified lines12312412512612712818 unmodified linesROOT_DIR = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT_DIR))from measure_finger import measure_fingerAPP_ROOT = Path(__file__).resolve().parentUPLOAD_DIR = APP_ROOT / "uploads"97 unmodified linessave_debug=False,)result_json_name = f"{run_id}__result.json"result_json_path = RESULTS_DIR / result_json_name_save_json(result_json_path, result)18 unmodified lines1920212223242597 unmodified lines12312412512612712812913013113213313413518 unmodified linesROOT_DIR = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT_DIR))from measure_finger import measure_finger, apply_calibrationAPP_ROOT = Path(__file__).resolve().parentUPLOAD_DIR = APP_ROOT / "uploads"97 unmodified linessave_debug=False,)# Apply calibrationraw_diameter = result.get("finger_outer_diameter_cm")if raw_diameter is not None:result["raw_diameter_cm"] = round(raw_diameter, 4)result["finger_outer_diameter_cm"] = round(apply_calibration(raw_diameter), 4)result["calibration_applied"] = Trueresult_json_name = f"{run_id}__result.json"result_json_path = RESULTS_DIR / result_json_name_save_json(result_json_path, result)
10 unmodified lines11121314151610 unmodified linesconst failReasonMessageMap = {card_not_detected:"Credit card not detected. Place a full card flat beside your hand.",hand_not_detected:"Hand not detected. Include your full palm in frame and keep fingers fully visible.",finger_isolation_failed:10 unmodified lines111213141516171810 unmodified linesconst failReasonMessageMap = {card_not_detected:"Credit card not detected. Place a full card flat beside your hand.",card_not_parallel:"Card is not parallel to the camera. Keep your phone directly above and parallel to the card.",hand_not_detected:"Hand not detected. Include your full palm in frame and keep fingers fully visible.",finger_isolation_failed:
README.md+54-62
measure_finger.py+43
script/analyze_calibration.pyAdded+323
script/batch_measure.pyAdded+177
script/deploy_hf.shAdded+21
src/calibration.jsonAdded+10
web_demo/app.py+8-1
web_demo/static/app.js+2