"""Robust feature-based global initialization.""" import cv2 import numpy as np from .common import gray, RegistrationError def estimate_global(reference, moving, allow_local=False): evidence = dict(matches=0, inliers=None, inlier_ratio=None, match_coverage=None) # Independently resize for matching; map the estimate back to original pixels. def features(image): scale = min(1., 1400 / max(image.shape[:2])) small = cv2.resize(image, None, fx=scale, fy=scale) g = gray(small) mask = ((g > 12) & (g < 245)).astype(np.uint8) * 255 keypoints, descriptors = cv2.SIFT_create(nfeatures=7000).detectAndCompute(g, mask) return keypoints, descriptors, scale kr, dr, sr = features(reference) km, dm, sm = features(moving) if dr is None or dm is None or min(len(dr), len(dm)) < 12: raise RegistrationError('Not enough visible detail to estimate alignment.', evidence) pairs = cv2.BFMatcher().knnMatch(dm, dr, k=2) good = [p[0] for p in pairs if len(p) == 2 and p[0].distance < .72 * p[1].distance] evidence['matches'] = len(good) if len(good) < 12: raise RegistrationError('Too few reliable feature matches. Try tighter iris crops.', evidence) source = np.float32([km[m.queryIdx].pt for m in good]) / sm target = np.float32([kr[m.trainIdx].pt for m in good]) / sr matrix, inliers = cv2.findHomography(source, target, cv2.RANSAC, (10 if allow_local else 3) / sr) if inliers is not None: evidence.update(inliers=int(inliers.sum()), inlier_ratio=float(inliers.mean())) if matrix is None or not np.isfinite(matrix).all() or inliers.sum() < 12 or inliers.mean() < .3: raise RegistrationError('Matches do not support a reliable global transformation.', evidence) selected = inliers.ravel().astype(bool) h, w = reference.shape[:2] # Require evidence distributed over a meaningful part of the image. coverage = cv2.contourArea(cv2.convexHull(target[selected])) / (h * w) evidence['match_coverage'] = float(coverage) if coverage < .08: raise RegistrationError('Matches are too concentrated to trust the transformation.', evidence) mh, mw = moving.shape[:2] corners = np.float32([[0, 0], [mw, 0], [mw, mh], [0, mh]]) denominators = (matrix @ np.c_[corners, np.ones(4)].T)[2] warped_corners = cv2.perspectiveTransform(corners[None], matrix)[0] area = cv2.contourArea(warped_corners, oriented=True) if np.any(denominators <= 0) or not .15 < area / (h*w) < 6: raise RegistrationError('Implausible or flipped transformation rejected.', evidence) error = np.linalg.norm(cv2.perspectiveTransform(source[selected, None], matrix)[:, 0] - target[selected], axis=1) return matrix, dict(matches=len(good), inliers=int(selected.sum()), inlier_ratio=float(selected.mean()), match_coverage=float(coverage), fit_error_px=float(np.median(error)))