128 lines
4.4 KiB
Python
128 lines
4.4 KiB
Python
'''
|
|
Filename: iqa_correlation_analysis.py
|
|
Path: /home/netoa/Desktop/ISR/scripts
|
|
Created Date: Monday March 24th 2025
|
|
Author: Andre Neto
|
|
-----
|
|
Last Modified: Tue Mar 25 2025
|
|
Modified By: Andre Neto
|
|
-----
|
|
Copyright (c) 2025 Institute of Systems and Robotics
|
|
'''
|
|
|
|
import os
|
|
import pandas as pd
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sns
|
|
import numpy as np
|
|
from scipy.stats import pearsonr, spearmanr
|
|
|
|
# pylint: disable=line-too-long
|
|
|
|
def load_iqa_data(objective_path: str, subjective_path: str) -> pd.DataFrame:
|
|
"""Load and merge objective and subjective IQA scores."""
|
|
obj_df = pd.read_csv(objective_path)
|
|
subj_df = pd.read_csv(subjective_path)[["file_name", "mos"]]
|
|
merged_df = obj_df.merge(subj_df, on="file_name", how="inner")
|
|
return merged_df
|
|
|
|
|
|
def compute_iqa_correlations(df: pd.DataFrame) -> pd.DataFrame:
|
|
"""Compute PLCC and SRCC for each IQA metric."""
|
|
metrics = df.drop(columns=["file_name", "mos"])
|
|
plcc, srcc = {}, {}
|
|
for metric in metrics.columns:
|
|
plcc[metric], _ = pearsonr(df[metric], df["mos"])
|
|
srcc[metric], _ = spearmanr(df[metric], df["mos"])
|
|
results_df = pd.DataFrame.from_dict(plcc, orient="index", columns=["PLCC"])
|
|
results_df["SRCC"] = pd.Series(srcc)
|
|
results_df = results_df.sort_values(by="PLCC", ascending=False)
|
|
return results_df
|
|
|
|
|
|
def plot_iqa_scatter(df: pd.DataFrame, output_dir: str, file_name: str = "metrics_scatter"):
|
|
"""Scatter plots of MOS vs each IQA metric with smoothed regression line."""
|
|
metrics = df.drop(columns=["file_name", "mos"])
|
|
num_metrics = len(metrics.columns)
|
|
cols = 5
|
|
rows = -(-num_metrics // cols)
|
|
|
|
fig, axes = plt.subplots(rows, cols, figsize=(16, rows * 3))
|
|
axes = axes.flatten()
|
|
|
|
for i, metric in enumerate(metrics.columns):
|
|
sns.scatterplot(x=df[metric], y=df["mos"], alpha=0.5, ax=axes[i], color="#87CEEB") # Lighter blue
|
|
x_sorted = df[metric].sort_values().values
|
|
y_sorted = df.loc[df[metric].sort_values().index, "mos"].values
|
|
z = np.polyfit(x_sorted, y_sorted, 3) # Fit a cubic curve
|
|
p = np.poly1d(z)
|
|
axes[i].plot(x_sorted, p(x_sorted), color="red", linewidth=2) # Red curve
|
|
axes[i].set_title(metric)
|
|
axes[i].set_xlabel("IQA Score")
|
|
axes[i].set_ylabel("MOS")
|
|
|
|
for j in range(num_metrics, len(axes)):
|
|
fig.delaxes(axes[j])
|
|
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
plt.tight_layout()
|
|
plt.savefig(os.path.join(output_dir, f"{file_name}.png"), dpi=300)
|
|
plt.savefig(os.path.join(output_dir, f"{file_name}.eps"), dpi=300)
|
|
plt.close()
|
|
|
|
|
|
def plot_iqa_bar(results_df: pd.DataFrame, output_dir: str, file_name: str = "metrics_bar"):
|
|
"""Bar chart ranking IQA metrics based on PLCC and SRCC."""
|
|
sorted_df = results_df.sort_values(by="PLCC", ascending=True)
|
|
|
|
plt.figure(figsize=(12, 8))
|
|
plt.barh(sorted_df.index, sorted_df["PLCC"], color="steelblue", label="PLCC")
|
|
plt.barh(sorted_df.index, sorted_df["SRCC"], color="orange", alpha=0.7, label="SRCC")
|
|
plt.xlabel("Correlation Coefficient")
|
|
plt.ylabel("IQA Metric")
|
|
plt.title("Ranking of IQA Metrics (PLCC & SRCC)")
|
|
plt.legend()
|
|
plt.grid(axis="x", linestyle="--", alpha=0.7)
|
|
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
plt.tight_layout()
|
|
plt.savefig(os.path.join(output_dir, f"{file_name}.png"), dpi=300)
|
|
plt.savefig(os.path.join(output_dir, f"{file_name}.eps"), dpi=300)
|
|
plt.close()
|
|
|
|
|
|
def save_iqa_results(results_df: pd.DataFrame, output_path: str):
|
|
"""Save correlation scores to CSV."""
|
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
results_df.to_csv(output_path, index_label="metric")
|
|
|
|
|
|
def main():
|
|
"""Run full IQA correlation analysis pipeline."""
|
|
# Input paths
|
|
objective_path = "results/sheets/iqa_objective.csv"
|
|
subjective_path = "results/sheets/iqa_subjective.csv"
|
|
|
|
# Output directory
|
|
output_dir = "results/fr_metrics"
|
|
csv_path = os.path.join(output_dir, "metrics_plcc_srcc.csv")
|
|
|
|
# Load and merge datasets
|
|
merged_df = load_iqa_data(objective_path, subjective_path)
|
|
|
|
# Compute correlation rankings
|
|
results_df = compute_iqa_correlations(merged_df)
|
|
|
|
# Generate visualizations
|
|
plot_iqa_scatter(merged_df, output_dir, "metrics_scatter")
|
|
plot_iqa_bar(results_df, output_dir, "metrics_bar")
|
|
|
|
# Save results
|
|
save_iqa_results(results_df, csv_path)
|
|
|
|
print("IQA Correlation Analysis Complete. Results saved to disk.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|