"""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