"""Orchestrate global alignment, optional local refinement, and compositing.""" import time import cv2 import numpy as np from .common import RegistrationError from .global_alignment import estimate_global from .local_alignment import refine_local from .compositing import compose def register(reference, moving, exposure=True, local=True, return_maps=False): started = time.perf_counter() # Prefer the strict estimate; only retry a broader residual tolerance when # local refinement is enabled. A coarse fallback must pass local validation. coarse = False try: matrix, metrics = estimate_global(reference, moving) except RegistrationError: if not local: raise matrix, metrics = estimate_global(reference, moving, allow_local=True) coarse = True h, w = reference.shape[:2] mh, mw = moving.shape[:2] global_image = cv2.warpPerspective(moving, matrix, (w,h)) valid = cv2.warpPerspective(np.ones((mh,mw), np.uint8), matrix, (w,h), flags=cv2.INTER_NEAREST) valid = cv2.erode(valid, np.ones((5,5), np.uint8)).astype(bool) if valid.mean() < .4: raise RegistrationError('Insufficient overlap between the photographs.', metrics) field, trusted, info = (None, np.ones((h,w), bool), dict(applied=False, reason='Disabled')) if local: field, trusted, info = refine_local(reference, global_image, valid) if coarse and field is None: raise RegistrationError('Coarse global alignment could not be verified by local refinement.', metrics) yy, xx = np.indices((h,w), dtype=np.float32) if field is not None: xx += field[...,0] yy += field[...,1] # Compose inverse homography with local backward flow, then sample ORIGINAL # moving pixels once. Avoid serial warping of the delivered output. inverse = np.linalg.inv(matrix) denominator = inverse[2,0]*xx + inverse[2,1]*yy + inverse[2,2] map_x = ((inverse[0,0]*xx + inverse[0,1]*yy + inverse[0,2]) / denominator).astype(np.float32) map_y = ((inverse[1,0]*xx + inverse[1,1]*yy + inverse[1,2]) / denominator).astype(np.float32) valid = np.isfinite(map_x) & np.isfinite(map_y) & (map_x >= 2) & (map_x < mw-3) & (map_y >= 2) & (map_y < mh-3) aligned = cv2.remap(moving, map_x, map_y, cv2.INTER_LINEAR) outputs, blend_metrics = compose(reference, aligned, valid, trusted, exposure) outputs['global_aligned'] = global_image outputs['local_confidence'] = trusted.astype(np.uint8)*255 outputs['deformation'] = np.zeros((h,w), np.uint8) if field is None else np.clip(np.linalg.norm(field,axis=2)*12,0,255).astype(np.uint8) metrics.update(blend_metrics) metrics.update(transform=matrix.tolist(), local=info, coarse_initialization=coarse, runtime_seconds=round(time.perf_counter()-started,3), warning='Confidence and blend masks are heuristic. Inspect real fibers. Global fit error is not independent accuracy; the homography excludes local deformation.') outputs['metrics'] = metrics if return_maps: outputs['sampling_map'] = np.stack([map_x,map_y],axis=-1) return outputs