Spaces:
Paused
Paused
Download scripts/benchmark_improvements.py from modventures/iris: direct link, hf CLI and curl.
- Browser
- Download file 5.43 kB
-
https://huggingface.co/spaces/modventures/iris/resolve/main/scripts/benchmark_improvements.py
- Command line
-
hf download hf://spaces/modventures/iris/scripts/benchmark_improvements.py
-
curl -L -o benchmark_improvements.py https://huggingface.co/spaces/modventures/iris/resolve/main/scripts/benchmark_improvements.py
5.43 kB
| """Reproducible ablations on private crops; no client images leave this machine.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from backend.experimental.matching import LearnedMatcher | |
| from backend.experimental.patch_validation import validate_patches | |
| from backend.experimental.preprocessing import iris_mask | |
| from backend.experimental.segmentation import adaptive_mask, geometry_overlay | |
| from backend.experimental.evaluation import evaluate_correspondences, common_evaluation | |
| from backend.experimental.radial import fit_radial_mesh | |
| from backend.experimental.mesh import dense_mesh | |
| from backend.experimental.native_refinement import refine_native | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--variants', nargs='+', default=['loftr800', 'loftr1024', 'lightglue1600']) | |
| parser.add_argument('--samples', nargs='+', type=int, default=list(range(1, 7))) | |
| parser.add_argument('--output', type=Path, default=ROOT/'private_benchmarks/improvements') | |
| args = parser.parse_args() | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| rows = [] | |
| for variant in args.variants: | |
| if variant not in {'loftr800', 'loftr1024', 'lightglue1600'}: | |
| parser.error('Unknown variant') | |
| matcher = None | |
| for sample in args.samples: | |
| started = time.perf_counter() | |
| folder = ROOT/'private_benchmarks/client_iris'/str(sample) | |
| ref, mov = (cv2.imread(str(folder/f'{n}.png')) for n in ('reference', 'moving')) | |
| dest = args.output/f'{sample}-{variant}' | |
| dest.mkdir(exist_ok=True) | |
| masks, geometries = zip(*(adaptive_mask(im) for im in (ref, mov))) | |
| for name, im, g, mask in zip(('reference', 'moving'), (ref, mov), geometries, masks): | |
| cv2.imwrite(str(dest/f'{name}-geometry.jpg'), geometry_overlay(im, g)) | |
| cv2.imwrite(str(dest/f'{name}-mask.png'), mask.astype(np.uint8)*255) | |
| cache = dest/'raw.npz' | |
| broad = tuple(iris_mask(im) | mask for im, mask in zip((ref, mov), masks)) | |
| signature = hashlib.sha256(ref.tobytes()+mov.tobytes()+b''.join(m.tobytes() for m in broad)+variant.encode()).hexdigest() | |
| manifest = dest/'cache.json' | |
| if cache.exists() and manifest.exists() and json.loads(manifest.read_text()).get('signature')==signature: | |
| with np.load(cache) as data: | |
| raw_a, raw_b = data['reference'], data['moving'] | |
| else: | |
| if matcher is None: | |
| if variant.startswith('loftr'): | |
| matcher = LearnedMatcher(ROOT/'models/loftr_outdoor.ckpt', max_size=int(variant[5:])) | |
| else: | |
| from backend.experimental.lightglue_matching import LightGlueMatcher | |
| matcher = LightGlueMatcher(ROOT/'models', max_size=1600) | |
| # Broad mask permits a fair fixed/adaptive mask comparison without reinference. | |
| raw_a, raw_b = matcher(ref, mov, masks=broad) | |
| np.savez_compressed(cache, reference=raw_a, moving=raw_b) | |
| manifest.write_text(json.dumps(dict(signature=signature,variant=variant),indent=2)) | |
| baseline = np.load(ROOT/f'private_benchmarks/research/{sample}-loftr_patch-matches.npz') | |
| anchors_a, anchors_b = baseline['reference'], baseline['moving'] | |
| for adaptive in (False, True): | |
| selected = masks if adaptive else (iris_mask(ref), iris_mask(mov)) | |
| keep = np.ones(len(raw_a), bool) | |
| for points, mask in zip((raw_a, raw_b), selected): | |
| xy = points.astype(int) | |
| keep &= mask[xy[:, 1], xy[:, 0]] | |
| for multiscale in (False, True): | |
| a, b = validate_patches(ref, mov, raw_a[keep], raw_b[keep], multiscale=multiscale) | |
| name = f'{"adaptive" if adaptive else "fixed"}-{"multi" if multiscale else "single"}' | |
| np.savez_compressed(dest/f'{name}.npz', reference=a, moving=b) | |
| row = dict(sample=sample, variant=variant, adaptive=adaptive, multiscale=multiscale, | |
| raw_matches=int(keep.sum()), verified_matches=len(a), | |
| geometries=[g.to_dict() if g else None for g in geometries], | |
| self_evaluation=evaluate_correspondences(a, b, ref.shape[:2]), | |
| common_evaluation=common_evaluation(a, b, anchors_a, anchors_b, ref.shape[:2])) | |
| if adaptive and geometries[0] is not None and geometries[0].limbus_detected: | |
| row['radial_common_evaluation'] = common_evaluation(a, b, anchors_a, anchors_b, ref.shape[:2], geometries[0]) | |
| rows.append(row) | |
| (args.output/'results.json').write_text(json.dumps(rows, indent=2)) | |
| print(json.dumps({k: row[k] for k in ['sample', 'variant', 'adaptive', 'multiscale', 'verified_matches', 'self_evaluation', 'common_evaluation']}), flush=True) | |
| print(f'Finished {sample} {variant}: {time.perf_counter()-started:.1f}s', flush=True) | |
| del matcher | |
| if __name__ == '__main__': | |
| main() | |