"""Validate coarse correspondences against native-resolution image patches.""" import cv2 import numpy as np from .preprocessing import normalize def validate_patches(reference,moving,ref_points,mov_points,multiscale=False): a,b=normalize(reference),normalize(moving) p=ref_points.astype(np.float32).reshape(-1,1,2) guess=mov_points.astype(np.float32).reshape(-1,1,2) if len(p)==0:return ref_points,mov_points args=dict(winSize=(41,41),maxLevel=2,criteria=(cv2.TERM_CRITERIA_EPS|cv2.TERM_CRITERIA_COUNT,50,.005),flags=cv2.OPTFLOW_USE_INITIAL_FLOW) q,ok,_=cv2.calcOpticalFlowPyrLK(a,b,p,guess.copy(),**args) reverse,back,_=cv2.calcOpticalFlowPyrLK(b,a,q,p.copy(),**args) fb=np.linalg.norm(reverse[:,0]-p[:,0],axis=1) shift=np.linalg.norm(q[:,0]-guess[:,0],axis=1) keep=ok.ravel().astype(bool)&back.ravel().astype(bool)&(fb<1)&(shift<12) h,w=b.shape margin=32 if multiscale else 25 keep &= np.isfinite(q[:,0]).all(axis=1)&np.isfinite(reverse[:,0]).all(axis=1) keep &= (q[:,0,0]>margin)&(q[:,0,0]margin)&(q[:,0,1]margin)&(p[:,0,0]margin)&(p[:,0,1].65 and min(scores)>(.4 if multiscale else .65) return p[keep,0],q[keep,0] def validate_geometry_patches(reference, moving, ref_points, mov_points, multiscale=True): """Validate in a common viewpoint, then return original moving coordinates. Translation-only patches can reject correct matches after camera rotation. This warp is an analysis copy, never a source for the delivered color image. """ from .evaluation import fit_geometry try: # Coarse matches initialize an analysis copy only. Final fitting retains # its 4px RANSAC threshold and unchanged held-out/geometry gates. matrix, _, _, _ = fit_geometry(ref_points, mov_points, reference.shape[:2], ransac_threshold=12) except (ValueError, cv2.error, np.linalg.LinAlgError): return np.empty((0, 2), np.float32), np.empty((0, 2), np.float32) h, w = reference.shape[:2] analysis_image = cv2.warpPerspective(moving, matrix, (w, h)) guesses = cv2.perspectiveTransform(mov_points[None], matrix)[0] a, b = validate_patches(reference, analysis_image, ref_points, guesses, multiscale=multiscale) if not len(a): return a, b b = cv2.perspectiveTransform(b[None], np.linalg.inv(matrix))[0] valid = np.isfinite(b).all(axis=1)&(b[:, 0]>32)&(b[:, 0]32)&(b[:, 1]