"""Spatial cross-validation of automatic correspondences, not anatomical ground truth.""" import cv2 import numpy as np from .mesh import fit_mesh, basis def fit_geometry(reference_points, moving_points, shape, ransac_threshold=4): if len(reference_points) < 24: raise ValueError('At least 24 verified correspondences are needed for geometry fitting.') matrix, inliers = cv2.findHomography(moving_points, reference_points, cv2.USAC_MAGSAC, ransac_threshold) if matrix is None or inliers is None or not np.isfinite(matrix).all() or inliers.sum() < 12 or inliers.mean() < .3: raise ValueError('Correspondences do not support stable geometry.') h,w=shape corners=np.float32([[0,0],[w,0],[w,h],[0,h]]) denominator=(matrix @ np.c_[corners,np.ones(4)].T)[2] projected=cv2.perspectiveTransform(corners[None],matrix)[0] if np.any(denominator<=0) or not .5= 60: for fold in range(5): test = folds(anchors_a)==fold train = folds(a)!=fold if test.sum() < 6: continue # Chunk distances to bound memory for dense feature sets. heldout = anchors_a[test] for start in range(0, len(a), 256): near = np.linalg.norm(a[start:start+256, None]-heldout[None], axis=2).min(axis=1) < 32 train[start:start+256] &= ~near try: if geometry is None: matrix, coef, _, _ = fit_geometry(a[train], b[train], shape) prediction = predict_points(heldout, matrix, coef, shape) else: from .radial import fit_radial_mesh prediction = fit_radial_mesh(a[train], b[train], shape, geometry).predict(heldout) errors[test] = np.linalg.norm(prediction-anchors_b[test], axis=1) except (ValueError, cv2.error, np.linalg.LinAlgError): pass return dict(count=len(errors), scored_count=int(np.isfinite(errors).sum()), median_px=float(np.median(errors)) if np.isfinite(errors).all() and len(errors) else None, p95_px=float(np.percentile(errors, 95)) if np.isfinite(errors).all() and len(errors) else None, within_px_percent={str(t): round(float((errors<=t).mean()*100), 2) if len(errors) else None for t in (1, 2, 3, 5)}, description='Fixed baseline automatic correspondences; five spatial folds with 32px training exclusion. Not anatomical ground truth. Unscored points count as failures.')