"""Bounded bidirectional optical flow on a capped working resolution. Maps point from reference coordinates into the globally aligned moving image. Confidence is heuristic; no claim of anatomical validation is made. """ import cv2 import numpy as np from .common import gray def refine_local(reference, global_image, valid): h, w = reference.shape[:2] scale = min(1., 1200 / max(h, w)) size = (round(w * scale), round(h * scale)) a = cv2.resize(gray(reference), size) b = cv2.resize(gray(global_image), size) overlap = cv2.resize(valid.astype(np.uint8), size, interpolation=cv2.INTER_NEAREST).astype(bool) usable = overlap & (a > 25) & (a < 230) & (b > 15) & (b < 240) gain = float(np.clip(np.median(a[usable] / np.maximum(b[usable], 1)), .4, 2.5)) if usable.any() else 1. b = np.clip(b.astype(np.float32) * gain, 0, 255).astype(np.uint8) # Stable neutral normalization is for correspondence only, never output pixels. def flow(first, second): return cv2.calcOpticalFlowFarneback(first, second, None, .5, 5, 31, 5, 7, 1.5, 0) forward = cv2.GaussianBlur(flow(a, b), (0, 0), 1.2) reverse = flow(b, a) yy, xx = np.indices(a.shape, dtype=np.float32) mx, my = xx + forward[..., 0], yy + forward[..., 1] back = cv2.remap(reverse, mx, my, cv2.INTER_LINEAR) fb = np.linalg.norm(forward + back, axis=2) displacement = np.linalg.norm(forward, axis=2) ux_y, ux_x = np.gradient(forward[..., 0]) uy_y, uy_x = np.gradient(forward[..., 1]) determinant = (1 + ux_x) * (1 + uy_y) - ux_y * uy_x strain = np.sqrt(ux_x**2 + ux_y**2 + uy_x**2 + uy_y**2) warped = cv2.remap(b, mx, my, cv2.INTER_LINEAR) before = cv2.GaussianBlur(cv2.absdiff(a, b).astype(np.float32), (0, 0), 2) after = cv2.GaussianBlur(cv2.absdiff(a, warped).astype(np.float32), (0, 0), 2) target_valid = cv2.remap(usable.astype(np.uint8), mx, my, cv2.INTER_NEAREST).astype(bool) trusted = usable & target_valid & (fb < 1.) & (displacement < 18.) & (determinant > .65) & (determinant < 1.5) & (strain < .45) & (after < 15) & (after <= before + 1) trusted = cv2.erode(trusted.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool) support = float(trusted.sum() / max(usable.sum(), 1)) improvement = float(1 - np.mean(after[trusted]) / max(np.mean(before[trusted]), .01)) if trusted.any() else 0. motion = float(np.median(displacement[trusted])) if trusted.any() else 0. accepted = support > .45 and improvement > .15 and motion > .3 info = dict(applied=accepted, trusted_fraction=support, photometric_improvement=improvement, median_displacement_working_px=motion, working_scale=scale, reason='Accepted constrained optical flow' if accepted else 'No reliable material improvement; kept global alignment') if not accepted: return None, np.ones((h,w), bool), info # Keep the smooth map continuous; gate source contribution, not the field, # at uncertain pixels to avoid discontinuities caused by zeroing local flow. dense = cv2.resize(forward, (w,h)) dense[..., 0] *= w / size[0] dense[..., 1] *= h / size[1] confidence = cv2.resize(trusted.astype(np.uint8), (w,h), interpolation=cv2.INTER_NEAREST).astype(bool) return dense, confidence, info