""" Module 4 – Facial Simulation via Landmark-Guided Gaussian RBF Warping. Applies procedure-specific morphological transformations directly to the target anatomical region of the uploaded photograph using a dense inverse displacement field and bicubic `cv2.remap`, preserving crisp skin texture and leaving non-target regions untouched. """ import os import cv2 import numpy as np from mfaf_net.module1_feature_extraction import REGION_INDICES # --------------------------------------------------------------------------- # Procedure-specific landmark displacement rules # Each entry: (group_name, axis, factor_rel_to_face, direction) # axis : 'x' or 'y' # factor : fraction of face width/height to displace # direction : +1 (down/right), -1 (up/left), or 'inward' (toward face centerline) # --------------------------------------------------------------------------- PROCEDURE_RULES = { 'rhinoplasty': [ ('nose_bridge_sides', 'x', 0.042, 'inward'), ('nose_alar', 'x', 0.055, 'inward'), ('nose_tip', 'y', 0.028, -1), ], 'blepharoplasty': [ ('upper_eyelid', 'y', 0.022, -1), ('lower_eyelid', 'y', 0.015, -1), ], 'rhytidectomy': [ ('jawline', 'y', 0.030, -1), ('jawline', 'x', 0.025, 'inward'), ('cheeks', 'y', 0.020, -1), ], 'genioplasty': [ ('chin_tip', 'y', 0.036, +1), ('chin_sides', 'x', 0.022, 'inward'), ], 'forehead_surgery': [ ('forehead', 'y', 0.026, -1), ('eyebrows', 'y', 0.012, -1), ], 'brow_lift': [ ('eyebrows', 'y', 0.032, -1), ], } LANDMARK_GROUPS = { 'nose_bridge_sides': [196, 3, 236, 198, 419, 248, 456, 420], 'nose_alar': [129, 98, 49, 209, 358, 327, 279, 429], 'nose_tip': [1, 2, 4, 5, 19, 94], 'upper_eyelid': [159, 160, 158, 157, 161, 223, 224, 386, 385, 387, 388, 384, 443, 444], 'lower_eyelid': [145, 144, 153, 154, 229, 230, 374, 373, 380, 381, 449, 450], 'jawline': [172, 136, 150, 149, 176, 58, 132, 397, 365, 379, 378, 400, 288, 361], 'cheeks': [205, 206, 50, 123, 425, 426, 280, 352], 'chin_tip': [152, 175, 199, 200], 'chin_sides': [148, 176, 377, 400], 'forehead': [10, 109, 67, 103, 54, 338, 297, 332, 284, 151, 9, 8], 'eyebrows': [70, 63, 105, 66, 107, 46, 53, 52, 65, 55, 300, 293, 334, 296, 336, 276, 283, 282, 295, 285], } # Anchor landmarks locked near zero displacement so adjacent features remain stable PROCEDURE_ANCHORS = { 'rhinoplasty': [133, 362, 33, 263, 0, 61, 291, 152], 'blepharoplasty': [33, 133, 362, 263, 1, 61, 291, 105, 334], 'rhytidectomy': [1, 33, 263, 61, 291, 13, 14, 152, 10], 'genioplasty': [14, 17, 61, 291, 1, 172, 397], 'forehead_surgery': [159, 386, 33, 263, 1, 152], 'brow_lift': [159, 386, 33, 263, 1, 10, 152], } # RBF influence radius as a fraction of face width (landmarks 234 <-> 454) PROCEDURE_SIGMA_RATIO = { 'rhinoplasty': 0.080, 'blepharoplasty': 0.055, 'rhytidectomy': 0.115, 'genioplasty': 0.095, 'forehead_surgery': 0.120, 'brow_lift': 0.075, } PROCEDURE_PRIMARY_REGION = { 'rhinoplasty': 'nose', 'blepharoplasty': 'eyes', 'rhytidectomy': 'jawline', 'genioplasty': 'chin', 'forehead_surgery': 'forehead', 'brow_lift': 'eyebrows', } CENTRE_X_IDX = 1 def _compute_patient_scale(patient_features: np.ndarray = None) -> float: """Derive an anatomical elasticity modulation factor from patient metadata.""" if patient_features is None or len(patient_features) < 10: return 1.0 age_norm = float(patient_features[0]) # [0, 1] tx_history = float(patient_features[9]) # 0 or 1 scale = 1.0 + 0.18 * (0.35 - age_norm) - 0.12 * tx_history return float(np.clip(scale, 0.78, 1.25)) def _compute_model_scale( trained_model, landmarks_array: np.ndarray, measurements: dict, patient_features: np.ndarray, procedure: str, h: int, w: int, ) -> float: """ Use the trained MFAFNetModel to derive a data-driven regional shift multiplier restricted strictly to the procedure's target landmarks (avoiding global drift). """ from mfaf_net.model_arch import predict_landmark_displacements dst_pred = predict_landmark_displacements( model=trained_model, landmarks_array=landmarks_array, measurements=measurements, patient_features=patient_features, procedure=procedure, img_h=h, img_w=w, ) region_name = PROCEDURE_PRIMARY_REGION.get(procedure, 'nose') indices = [i for i in REGION_INDICES.get(region_name, []) if i < len(landmarks_array)] if not indices: return 1.0 face_w = max(float(np.linalg.norm(landmarks_array[454] - landmarks_array[234])), 1.0) mean_shift = float(np.mean(np.linalg.norm(dst_pred[indices] - landmarks_array[indices], axis=1))) # Normalize learned shift relative to face width into a smooth [0.85, 1.35] multiplier ratio = mean_shift / (0.04 * face_w) return float(np.clip(0.85 + 0.35 * np.tanh(ratio), 0.85, 1.35)) def _apply_displacements( landmarks: np.ndarray, procedure: str, h: int, w: int, patient_features: np.ndarray = None, extra_scale: float = 1.0, ) -> np.ndarray: """Return a modified copy of landmarks with procedure-specific displacements applied.""" dst = landmarks.copy() rules = PROCEDURE_RULES.get(procedure, []) centre_x = float(landmarks[CENTRE_X_IDX, 0]) face_w = max(float(np.linalg.norm(landmarks[454] - landmarks[234])), 1.0) face_h = max(float(np.linalg.norm(landmarks[152] - landmarks[10])), 1.0) scale = _compute_patient_scale(patient_features) * float(extra_scale) for group_name, axis, factor, direction in rules: indices = LANDMARK_GROUPS.get(group_name, []) scaled_factor = factor * scale if axis == 'y': shift = scaled_factor * face_h * direction for idx in indices: if idx < len(dst): dst[idx, 1] += shift elif axis == 'x': magnitude = scaled_factor * face_w if direction == 'inward': for idx in indices: if idx < len(dst): cx = dst[idx, 0] shift = magnitude if cx > centre_x else -magnitude dst[idx, 0] -= shift else: shift = magnitude * direction for idx in indices: if idx < len(dst): dst[idx, 0] += shift dst[:, 0] = np.clip(dst[:, 0], 0, w - 1) dst[:, 1] = np.clip(dst[:, 1], 0, h - 1) return dst def _rbf_remap_warp( src_img: np.ndarray, src_pts: np.ndarray, dst_pts: np.ndarray, procedure: str, ) -> np.ndarray: """ Smooth, artifact-free image warp using a Gaussian RBF inverse displacement field and `cv2.remap(..., cv2.INTER_CUBIC)`. Pixels outside the procedure's influence radius stay bit-for-bit identical to `src_img`. """ h, w = src_img.shape[:2] deltas = dst_pts - src_pts mag = np.linalg.norm(deltas, axis=1) active_idx = np.where(mag > 0.25)[0] if len(active_idx) == 0: return src_img.copy() face_w = max(float(np.linalg.norm(src_pts[454] - src_pts[234])), float(min(h, w)) * 0.4) sigma = max(PROCEDURE_SIGMA_RATIO.get(procedure, 0.08) * face_w, 8.0) inv_2sig2 = 1.0 / (2.0 * sigma * sigma) # Coordinate grid grid_x, grid_y = np.meshgrid( np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32), ) disp_x = np.zeros((h, w), dtype=np.float32) disp_y = np.zeros((h, w), dtype=np.float32) weight_sum = np.zeros((h, w), dtype=np.float32) for idx in active_idx: px, py = float(src_pts[idx, 0]), float(src_pts[idx, 1]) dx, dy = float(deltas[idx, 0]), float(deltas[idx, 1]) d2 = (grid_x - px) ** 2 + (grid_y - py) ** 2 w_k = np.exp(-d2 * inv_2sig2) disp_x += w_k * dx disp_y += w_k * dy weight_sum += w_k # Normalize overlapping control weights smoothly without boosting far-field noise norm_factor = np.maximum(weight_sum, 1.0) disp_x /= norm_factor disp_y /= norm_factor # Anchor suppression so nearby stable landmarks (e.g. eye corners, lips) stay locked anchor_sigma = max(0.045 * face_w, 6.0) inv_2asig2 = 1.0 / (2.0 * anchor_sigma * anchor_sigma) anchor_mask = np.ones((h, w), dtype=np.float32) for a_idx in PROCEDURE_ANCHORS.get(procedure, []): if a_idx < len(src_pts) and a_idx not in active_idx: ax, ay = float(src_pts[a_idx, 0]), float(src_pts[a_idx, 1]) ad2 = (grid_x - ax) ** 2 + (grid_y - ay) ** 2 anchor_mask *= (1.0 - 0.92 * np.exp(-ad2 * inv_2asig2)) disp_x *= anchor_mask disp_y *= anchor_mask map_x = np.clip(grid_x - disp_x, 0.0, float(w - 1)).astype(np.float32) map_y = np.clip(grid_y - disp_y, 0.0, float(h - 1)).astype(np.float32) return cv2.remap( src_img, map_x, map_y, interpolation=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REFLECT_101, ) def _piecewise_affine_warp( src_img: np.ndarray, src_pts: np.ndarray, dst_pts: np.ndarray, procedure: str = 'rhinoplasty', ) -> np.ndarray: """Compatibility wrapper forwarding to the artifact-free RBF remap warp.""" return _rbf_remap_warp(src_img, src_pts, dst_pts, procedure=procedure) def simulate_procedure( original_path: str, landmarks_array: np.ndarray, regions: dict, procedure: str, output_dir: str, uid: str, patient_features: np.ndarray = None, attention_weights: dict = None, measurements: dict = None, ) -> dict: """ Apply landmark-guided facial simulation to produce a crisp simulated image. Uses the trained PyTorch MFAFNetModel (`models/mfaf_net_best.pt`) when available to modulate the procedure-specific anatomical displacement, falling back seamlessly to patient-scaled geometric rules if no checkpoint is present. """ image = cv2.imread(original_path) if image is None: raise ValueError(f"Cannot read image: {original_path}") h, w = image.shape[:2] src_pts = landmarks_array[:468].copy() simulation_mode = 'rule_based_geometric' model_scale = 1.0 try: from mfaf_net.model_arch import load_trained_model trained_model, _ = load_trained_model() if trained_model is not None and patient_features is not None and measurements is not None: model_scale = _compute_model_scale( trained_model=trained_model, landmarks_array=src_pts, measurements=measurements, patient_features=patient_features, procedure=procedure, h=h, w=w, ) simulation_mode = 'trained_mfaf_net' except Exception: model_scale = 1.0 dst_pts = _apply_displacements( src_pts, procedure, h, w, patient_features=patient_features, extra_scale=model_scale, ) result = _rbf_remap_warp(image, src_pts, dst_pts, procedure=procedure) sim_filename = f'simulated_{uid}.png' sim_path = os.path.join(output_dir, sim_filename) cv2.imwrite(sim_path, result) return { 'simulated_image_path': sim_path, 'simulation_mode': simulation_mode, }