"""Opt-in learned registration for explicitly confirmed, centered square iris crops.""" import hashlib import os import time from functools import lru_cache from pathlib import Path import cv2 import numpy as np from .common import RegistrationError from .compositing import compose from .experimental.matching import LearnedMatcher from .experimental.patch_validation import validate_patches,validate_geometry_patches from .experimental.settings import LearnedSettings from .experimental.segmentation import adaptive_mask,geometry_overlay from .experimental.preprocessing import iris_mask,glare_mask from .experimental.evaluation import evaluate_correspondences,fit_geometry from .experimental.mesh import dense_mesh @lru_cache(maxsize=1) def get_matcher(): settings=LearnedSettings.from_env() if settings.matcher=='lightglue': try: from .experimental.lightglue_matching import LightGlueMatcher return LightGlueMatcher(os.environ.get('IRIS_WEIGHTS_DIR',str(Path(__file__).resolve().parents[1]/'models')),max_size=settings.max_size) except (ImportError,FileNotFoundError) as exc: raise RuntimeError('LightGlue dependencies or offline weights are not installed.') from exc path=Path(os.environ.get('IRIS_MODEL_PATH',str(Path(__file__).resolve().parents[1]/'models/loftr_outdoor.ckpt'))) if not path.is_file():raise RuntimeError('Learned matcher weights are not installed on this server.') if hashlib.sha256(path.read_bytes()).hexdigest()!='21f5bec5968178e8bc8b7633441836fe5de4f47d861dd2cd7dc38e271b0479ec': raise RuntimeError('Learned matcher checkpoint failed integrity verification.') try:return LearnedMatcher(path,max_size=settings.max_size) except ImportError as exc:raise RuntimeError('Learned matcher dependencies are not installed.') from exc def register_learned(reference,moving,exposure=True,local=True): started=time.perf_counter() if not local:raise RegistrationError("The experimental learned engine requires local refinement.") h,w=reference.shape[:2] if reference.shape!=moving.shape or h!=w or not 400<=w<=3000: raise RegistrationError('Experimental alignment needs equally sized, centered square iris crops between 400 and 3000 pixels.') settings=LearnedSettings.from_env() geometries=(None,None) if settings.adaptive_mask: (roi,ref_geometry),(source_roi,mov_geometry)=adaptive_mask(reference),adaptive_mask(moving) geometries=(ref_geometry,mov_geometry) raw_ref,raw_mov=get_matcher()(reference,moving,masks=(roi,source_roi)) else: roi,source_roi=iris_mask(reference),iris_mask(moving) raw_ref,raw_mov=get_matcher()(reference,moving) if settings.patches=='geometry': ref,mov=validate_geometry_patches(reference,moving,raw_ref,raw_mov) elif settings.patches=='multiscale': ref,mov=validate_patches(reference,moving,raw_ref,raw_mov,multiscale=True) else: ref,mov=validate_patches(reference,moving,raw_ref,raw_mov) evaluation=evaluate_correspondences(ref,mov,(h,w)) metrics=dict(matches=len(raw_ref),verified_matches=len(ref),inliers=None,inlier_ratio=None, patch_survival_percent=round(100*len(ref)/max(len(raw_ref),1),1),evaluation=evaluation, engine='learned_experimental',settings=dict(matcher=settings.matcher,max_size=settings.max_size,patches=settings.patches,adaptive_mask=settings.adaptive_mask), segmentation=[g.to_dict() if g is not None else None for g in geometries]) # Preview eligibility is NOT a production accuracy or 95% success gate. if evaluation['p95_px'] is None or evaluation['median_px']>=4 or evaluation['p95_px']>=12: raise RegistrationError('The learned alignment did not pass correspondence validation. Reference preserved.',metrics) try:matrix,coef,inliers,coverage=fit_geometry(ref,mov,(h,w)) except ValueError as exc:raise RegistrationError(str(exc),metrics) from exc metrics.update(inliers=int(inliers.sum()),inlier_ratio=float(inliers.mean()),matches=len(ref),match_coverage=float(coverage)) if not local:coef=np.zeros_like(coef) mapping,geometry_valid,delta=dense_mesh(coef,matrix,(h,w)) if geometry_valid[roi].mean()<.99:raise RegistrationError('Local deformation exceeds the permitted geometry limits.',metrics) # Exactly one interpolation of original color pixels for the delivered warp. aligned=cv2.remap(moving,mapping[...,0],mapping[...,1],cv2.INTER_LINEAR) moving_roi=cv2.remap(source_roi.astype(np.uint8),mapping[...,0],mapping[...,1],cv2.INTER_NEAREST)>0 support=np.zeros((h,w),np.uint8) # Only allow source contribution close to observed correspondence locations. for point in ref:cv2.circle(support,tuple(np.rint(point).astype(int)),max(5,round(w*.04)),1,-1) trusted=roi&moving_roi&geometry_valid&support.astype(bool)&~glare_mask(reference)&~glare_mask(aligned) images,blend=compose(reference,aligned,geometry_valid,trusted,exposure) images['local_confidence']=trusted.astype(np.uint8)*255 images['deformation']=np.clip(np.linalg.norm(delta,axis=2)*12,0,255).astype(np.uint8) if settings.adaptive_mask: images['reference_geometry']=geometry_overlay(reference,geometries[0]) images['moving_geometry']=geometry_overlay(moving,geometries[1]) metrics.update(blend,fit_error_px=None,transform=matrix.tolist(),mesh_coefficients=coef.tolist(),reference_shape=[h,w],sampling_convention="inverse homography plus bilinear reference-grid residual",local={'applied':local}, runtime_seconds=round(time.perf_counter()-started,3), warning='Experimental alignment. Percentages describe automatic correspondence consistency, not anatomical accuracy. Glare and unknown regions remain reference-only. Global transform excludes the local mesh.', geometry_valid_fraction=float(geometry_valid[roi].mean()), raw_matches=len(raw_ref)) images['metrics']=metrics return images