"""A bounded pupil-centered radial residual prior, fitted only to training matches. The displacement peaks at the pupil boundary and falls to zero at the limbus. Unlike biometric texture unwrapping, this changes coordinates only. It assumes approximately circular boundaries and uniform radial strain; a mesh fits residuals. """ from dataclasses import dataclass import cv2 import numpy as np from .mesh import basis, fit_mesh from .evaluation import fit_geometry def radial_vectors(points, matrix, geometry): points = np.asarray(points, np.float32) base = cv2.perspectiveTransform(points[None], np.linalg.inv(matrix))[0] center = cv2.perspectiveTransform(np.float32([[geometry.center]]), np.linalg.inv(matrix))[0, 0] radius = np.linalg.norm(points-np.float32(geometry.center), axis=1) weight = np.where(radius < geometry.pupil_radius, radius/geometry.pupil_radius, np.clip((geometry.iris_radius-radius)/(geometry.iris_radius-geometry.pupil_radius), 0, 1)) direction = base-center direction /= np.maximum(np.linalg.norm(direction, axis=1, keepdims=True), 1e-6) return direction*weight[:, None] @dataclass class RadialMesh: matrix: np.ndarray coefficients: np.ndarray geometry: object amplitude: float shape: tuple def predict(self, points): base = cv2.perspectiveTransform(np.float32(points)[None], np.linalg.inv(self.matrix))[0] return base + self.amplitude*radial_vectors(points, self.matrix, self.geometry) + basis(points, self.shape) @ self.coefficients.reshape(-1, 2) def fit_radial_mesh(reference_points, moving_points, shape, geometry): matrix, _, _, _ = fit_geometry(reference_points, moving_points, shape) base = cv2.perspectiveTransform(reference_points[None], np.linalg.inv(matrix))[0] vectors = radial_vectors(reference_points, matrix, geometry) residual = moving_points-base weight = np.ones(len(vectors)) amplitude = 0. for _ in range(6): amplitude = float(np.sum(weight[:, None]*vectors*residual)/(np.sum(weight[:, None]*vectors**2)+1)) amplitude = float(np.clip(amplitude, -min(shape)*.04, min(shape)*.04)) error = np.linalg.norm(residual-amplitude*vectors, axis=1) weight = np.minimum(1, 3/np.maximum(error, 1e-6)) coefficients = fit_mesh(reference_points, moving_points-amplitude*vectors, matrix, shape) return RadialMesh(matrix, coefficients, geometry, amplitude, shape)