Instructions to use haresh2792005/MFAF-Net with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MediaPipe
How to use haresh2792005/MFAF-Net with MediaPipe:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
File size: 4,757 Bytes
c4a514c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | """
Module 5 – Result Comparison.
Compares the original and simulated facial images using pixel-level
difference maps and standard image quality metrics, and generates a
matplotlib summary chart.
"""
import os
import cv2
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from skimage.metrics import structural_similarity, peak_signal_noise_ratio
def compare_results(
original_path: str,
simulated_path: str,
output_dir: str,
uid: str,
) -> dict:
"""
Compute comparison metrics and generate visualisation assets.
Parameters
----------
original_path : str Absolute path to the original image.
simulated_path : str Absolute path to the simulated image.
output_dir : str Directory to save output assets.
uid : str Unique run identifier.
Returns
-------
dict with keys:
diff_map_path – absolute path to the heatmap PNG
metrics_chart_path – absolute path to the matplotlib summary PNG
metrics – dict of scalar float metrics
"""
orig = cv2.imread(original_path)
sim = cv2.imread(simulated_path)
if orig is None:
raise ValueError(f"Cannot read original image: {original_path}")
if sim is None:
raise ValueError(f"Cannot read simulated image: {simulated_path}")
# Resize simulated to original size if needed
if orig.shape != sim.shape:
sim = cv2.resize(sim, (orig.shape[1], orig.shape[0]))
# --- Absolute difference ---
diff = cv2.absdiff(orig, sim)
diff_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
# Suppress tiny interpolation rounding noise (< 3) and amplify surgical deltas for clear visual inspection
diff_vis = np.where(diff_gray >= 3, np.clip(diff_gray.astype(np.float32) * 3.5, 0, 255), 0).astype(np.uint8)
heatmap = cv2.applyColorMap(diff_vis, cv2.COLORMAP_JET)
diff_map_filename = f'diff_map_{uid}.png'
diff_map_path = os.path.join(output_dir, diff_map_filename)
cv2.imwrite(diff_map_path, heatmap)
# --- Metrics ---
# changed_pixel_pct: % pixels where ANY channel diff > 15
changed_mask = np.any(diff > 15, axis=2)
changed_pixel_pct = float(changed_mask.sum()) / float(changed_mask.size) * 100.0
# MAE
mae = float(np.mean(diff.astype(np.float32)))
# SSIM (multichannel)
orig_rgb = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)
sim_rgb = cv2.cvtColor(sim, cv2.COLOR_BGR2RGB)
ssim_val = float(structural_similarity(
orig_rgb, sim_rgb,
channel_axis=2,
data_range=255,
))
# PSNR
try:
psnr_val = float(peak_signal_noise_ratio(orig_rgb, sim_rgb, data_range=255))
except Exception:
psnr_val = 0.0
metrics = {
'changed_pixel_pct': round(changed_pixel_pct, 4),
'mae': round(mae, 4),
'ssim': round(ssim_val, 4),
'psnr': round(psnr_val, 4),
}
# --- Matplotlib chart ---
fig, axes = plt.subplots(1, 4, figsize=(18, 5))
fig.suptitle('MFAF-Net – Facial Simulation Comparison', fontsize=14, fontweight='bold')
axes[0].imshow(orig_rgb)
axes[0].set_title('Original')
axes[0].axis('off')
axes[1].imshow(sim_rgb)
axes[1].set_title('Simulated')
axes[1].axis('off')
heatmap_rgb = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
axes[2].imshow(heatmap_rgb)
axes[2].set_title('Difference Heatmap')
axes[2].axis('off')
# Metrics bar chart
metric_names = ['Changed\nPixels %', 'MAE', 'SSIM', 'PSNR (dB)']
metric_values = [
changed_pixel_pct,
mae,
ssim_val * 100, # scale to 0-100 for visual clarity
min(psnr_val, 60), # cap at 60 dB for display
]
colors = ['#e74c3c', '#e67e22', '#2ecc71', '#3498db']
bars = axes[3].bar(metric_names, metric_values, color=colors, edgecolor='black')
axes[3].set_title('Quality Metrics')
axes[3].set_ylabel('Value')
for bar, val in zip(bars, metric_values):
axes[3].text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.5,
f'{val:.2f}',
ha='center', va='bottom', fontsize=9,
)
# Annotate SSIM note
axes[3].text(
0.5, -0.12,
'* SSIM shown as ×100 for scale; PSNR capped at 60 dB',
transform=axes[3].transAxes,
ha='center', fontsize=7, style='italic', color='gray',
)
plt.tight_layout()
chart_filename = f'metrics_chart_{uid}.png'
chart_path = os.path.join(output_dir, chart_filename)
plt.savefig(chart_path, dpi=120, bbox_inches='tight')
plt.close(fig)
return {
'diff_map_path': diff_map_path,
'metrics_chart_path': chart_path,
'metrics': metrics,
}
|