MFAF-Net / mfaf_net /module5_comparison.py
haresh2792005's picture
Upload MFAF-Net (model)
c4a514c verified
Raw History Blame Contribute Delete
4.76 kB
"""
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,
}