MFAF-Net / mfaf_net /module3_feature_fusion.py
haresh2792005's picture
Upload MFAF-Net (model)
c4a514c verified
Raw History Blame Contribute Delete
3.2 kB
"""
Module 3 – Procedure-aware Feature Fusion.
Fuses flattened facial landmark coordinates, scalar measurements, and
patient features into a single fused representation using procedure-specific
attention weights that amplify the clinically relevant facial region.
"""
import numpy as np
from mfaf_net.module1_feature_extraction import REGION_INDICES as REGION_LANDMARK_RANGES
PROCEDURE_ATTENTION = {
'rhinoplasty': {'nose': 3.0, 'eyes': 1.0, 'eyebrows': 1.0, 'chin': 1.0, 'jawline': 1.0, 'forehead': 1.0},
'blepharoplasty': {'nose': 1.0, 'eyes': 3.0, 'eyebrows': 1.5, 'chin': 1.0, 'jawline': 1.0, 'forehead': 1.0},
'rhytidectomy': {'nose': 1.0, 'eyes': 1.0, 'eyebrows': 1.0, 'chin': 1.5, 'jawline': 3.0, 'forehead': 1.0},
'genioplasty': {'nose': 1.0, 'eyes': 1.0, 'eyebrows': 1.0, 'chin': 3.0, 'jawline': 1.5, 'forehead': 1.0},
'forehead_surgery': {'nose': 1.0, 'eyes': 1.0, 'eyebrows': 1.5, 'chin': 1.0, 'jawline': 1.0, 'forehead': 3.0},
'brow_lift': {'nose': 1.0, 'eyes': 1.5, 'eyebrows': 3.0, 'chin': 1.0, 'jawline': 1.0, 'forehead': 1.5},
}
def fuse_features(
landmarks_array: np.ndarray,
measurements: dict,
patient_features: np.ndarray,
procedure: str,
) -> dict:
"""
Fuse landmark, measurement, and patient features with attention weighting.
Parameters
----------
landmarks_array : np.ndarray shape (468, 2) pixel coordinates
measurements : dict scalar float measurements
patient_features: np.ndarray shape (12,) from module2
procedure : str procedure id
Returns
-------
dict with keys:
fused_vector – np.ndarray (flattened weighted landmark coords +
normalised measurements + patient features)
attention_weights – dict region → float weight
"""
attention = PROCEDURE_ATTENTION.get(procedure, {r: 1.0 for r in REGION_LANDMARK_RANGES})
# Build per-landmark weight array (shape 468,)
lm_weights = np.ones(468, dtype=np.float32)
for region, indices in REGION_LANDMARK_RANGES.items():
w = attention.get(region, 1.0)
for idx in indices:
if idx < 468:
lm_weights[idx] = max(lm_weights[idx], w)
# Flatten and apply weights: (468, 2) → (936,), weight each pair
lm_flat = landmarks_array.flatten() # shape (936,)
weight_flat = np.repeat(lm_weights, 2) # shape (936,)
weighted_lm = lm_flat * weight_flat
# Normalise landmarks to [0, 1] using min-max
lm_max = weighted_lm.max() if weighted_lm.max() != 0 else 1.0
weighted_lm_norm = weighted_lm / lm_max
# Measurement vector (sorted by key for determinism)
meas_values = np.array(
[float(v) for _, v in sorted(measurements.items())],
dtype=np.float32,
)
meas_max = meas_values.max() if meas_values.max() != 0 else 1.0
meas_norm = meas_values / meas_max
# Concatenate all features
fused_vector = np.concatenate([weighted_lm_norm, meas_norm, patient_features])
return {
'fused_vector': fused_vector,
'attention_weights': {k: float(v) for k, v in attention.items()},
}