"""Regularized bilinear correspondence mesh with robust residual fitting. Fits training correspondences only. Callers must validate held-out matches and inspect image detail; estimated matches are not anatomical ground truth. """ import cv2 import numpy as np def basis(points,shape,side=9): h,w=shape q=points/np.float32([w-1,h-1])*(side-1) q=np.clip(q,0,side-1) ix=np.minimum(np.floor(q).astype(int),side-2);frac=q-ix a=np.zeros((len(points),side*side),np.float64) for dy,dx in [(0,0),(0,1),(1,0),(1,1)]: weight=(frac[:,0] if dx else 1-frac[:,0])*(frac[:,1] if dy else 1-frac[:,1]) a[np.arange(len(points)),(ix[:,1]+dy)*side+ix[:,0]+dx]=weight return a def fit_mesh(reference_points,moving_points,homography,shape,side=9): if len(reference_points)<24:raise ValueError('Too few mesh constraints') inverse=np.linalg.inv(homography) prediction=cv2.perspectiveTransform(reference_points[None],inverse)[0] residual=moving_points-prediction a=basis(reference_points,shape,side) # Penalize second differences, favoring smooth local motion over isolated bends. penalties=[] for y in range(side): for x in range(side): for dy,dx in [(0,1),(1,0)]: if y+2*dy0)&np.isfinite(full_jac)&(mx>=0)&(mx=0)&(my.65)&(jac<1.5)&(strain<.45) return np.stack([mx,my],-1),good,delta