Initial clean commit
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
'''
|
||||
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()
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
This script processes reference and distorted images, computes various image quality metrics
|
||||
from the `metrics` modules, and writes the results to a CSV file as they are computed.
|
||||
|
||||
It loops through reference images, finds corresponding distorted images, and computes
|
||||
metrics for each pair using the `compute_all` function from the appropriate modules.
|
||||
|
||||
Metrics include various quality assessment methods such as:
|
||||
- Color-based metrics (C-SSIM, FSIMc, VIFc)
|
||||
- Structural-based metrics (SSIM, MS-SSIM, G-SSIM, IW-SSIM)
|
||||
- Gradient-based metrics (GMSD, G-SSIM, ESIM)
|
||||
- Frequency-based metrics (FIQ, SRSIM, ERGAS, SAM)
|
||||
- Wavelet-based metrics (W-SSIM, CW-SSIM, SPIQ)
|
||||
- Perceptual-based metrics (VSNR, PIQE, UQI, PQM)
|
||||
- Pixel-based metrics (MSE, PSNR, SNR, MAE)
|
||||
- Information-theoretic metrics (VIF, VIFp)
|
||||
- Model-based metrics (LPIPS, DISTS)
|
||||
|
||||
Functions:
|
||||
- process_imgs: Loops through the images, computes metrics, and writes to a CSV file.
|
||||
- main: Defines directories for images and the output file, then calls `process_imgs`.
|
||||
|
||||
Modules used:
|
||||
- metrics.color: Contains color-based metrics computation.
|
||||
- metrics.structural: Contains SSIM-based metrics computation.
|
||||
- metrics.gradient: Contains gradient-based metrics computation.
|
||||
- metrics.frequency: Contains frequency domain metrics computation.
|
||||
- metrics.wavelet: Contains wavelet-based metrics computation.
|
||||
- metrics.perceptual: Contains perceptual-based metrics computation.
|
||||
- metrics.pixel: Contains pixel-based metrics computation.
|
||||
- metrics.information: Contains information-theoretic metrics computation.
|
||||
"""
|
||||
|
||||
import os
|
||||
import csv
|
||||
|
||||
from metrics.objective.full_reference import color
|
||||
from metrics.objective.full_reference import frequency
|
||||
from metrics.objective.full_reference import gradient
|
||||
from metrics.objective.full_reference import information
|
||||
from metrics.objective.full_reference import models
|
||||
from metrics.objective.full_reference import perceptual
|
||||
from metrics.objective.full_reference import pixel
|
||||
from metrics.objective.full_reference import region
|
||||
from metrics.objective.full_reference import structural
|
||||
from metrics.objective.full_reference import wavelet
|
||||
|
||||
def compute(ref_dir, dist_dir, out_file):
|
||||
"""
|
||||
Processes reference and distorted images, computes various image quality metrics,
|
||||
and appends the results to a CSV file as they are computed.
|
||||
|
||||
Parameters:
|
||||
ref_dir (str): Path to the directory containing reference images.
|
||||
dist_dir (str): Path to the directory containing distorted images.
|
||||
out_file (str): Path to the output CSV file where the results will be saved.
|
||||
"""
|
||||
print("Initializing processing of images...")
|
||||
print(f"Reference directory: {ref_dir}")
|
||||
print(f"Distorted directory: {dist_dir}")
|
||||
print(f"Output file: {out_file}")
|
||||
|
||||
ref_imgs = sorted([f for f in os.listdir(ref_dir) if os.path.isfile(os.path.join(ref_dir, f))])
|
||||
print(f"Found {len(ref_imgs)} reference images.")
|
||||
|
||||
header_written = False # Flag to check if the header has been written
|
||||
|
||||
with open(out_file, mode='a', newline='', encoding='utf-8') as file:
|
||||
writer = csv.writer(file)
|
||||
|
||||
for ref_idx, ref_img in enumerate(ref_imgs, start=1):
|
||||
ref_img_path = os.path.join(ref_dir, ref_img)
|
||||
img_name = ref_img.rsplit('.', 1)[0]
|
||||
|
||||
print(f"\nProcessing reference image {ref_idx}/{len(ref_imgs)}: {ref_img}")
|
||||
|
||||
# Find all distorted images for the current reference image
|
||||
dist_imgs = sorted([f for f in os.listdir(dist_dir) if f.startswith(img_name)])
|
||||
print(f" Found {len(dist_imgs)} distorted images for {ref_img}.")
|
||||
|
||||
for dist_idx, dist_img in enumerate(dist_imgs, start=1):
|
||||
dist_img_path = os.path.join(dist_dir, dist_img)
|
||||
print(f" - Processing distorted image {dist_idx}/{len(dist_imgs)}: {dist_img}")
|
||||
|
||||
# Compute metrics
|
||||
color_results = color.compute_all(ref_img_path, dist_img_path)
|
||||
frequency_results = frequency.compute_all(ref_img_path, dist_img_path)
|
||||
gradient_results = gradient.compute_all(ref_img_path, dist_img_path)
|
||||
information_results = information.compute_all(ref_img_path, dist_img_path)
|
||||
models_results = models.compute_all(ref_img_path, dist_img_path)
|
||||
perceptual_results = perceptual.compute_all(ref_img_path, dist_img_path)
|
||||
pixel_results = pixel.compute_all(ref_img_path, dist_img_path)
|
||||
region_results = region.compute_all(ref_img_path, dist_img_path)
|
||||
structural_results = structural.compute_all(ref_img_path, dist_img_path)
|
||||
wavelet_results = wavelet.compute_all(ref_img_path, dist_img_path)
|
||||
|
||||
# Combine all metric results into a single dictionary
|
||||
combined_results = {
|
||||
**color_results,
|
||||
**frequency_results,
|
||||
**gradient_results,
|
||||
**information_results,
|
||||
**models_results,
|
||||
**perceptual_results,
|
||||
**pixel_results,
|
||||
**region_results,
|
||||
**structural_results,
|
||||
**wavelet_results,
|
||||
}
|
||||
|
||||
# Prepare header and result row
|
||||
metric_names = ['file_name'] + list(combined_results.keys())
|
||||
img_name = dist_img.rsplit('.', 1)[0]
|
||||
result_row = [img_name] + [f"{val[0]:.8g}" for val in combined_results.values()]
|
||||
|
||||
# Write header if not already written
|
||||
if not header_written:
|
||||
writer.writerow(metric_names)
|
||||
header_written = True
|
||||
|
||||
# Write the result row
|
||||
writer.writerow(result_row)
|
||||
|
||||
print(f"Successfully processed and saved metrics for {img_name}")
|
||||
|
||||
print("\nProcessing complete! Results saved to:", out_file)
|
||||
|
||||
|
||||
def main():
|
||||
'''main function'''
|
||||
#reference_dir = 'images/reference/'
|
||||
#distorted_dir = 'images/distorted/'
|
||||
#output_file = 'results/sheets/iqa_objective.csv'
|
||||
|
||||
# If you want to start fresh, uncomment the following line to clear the file
|
||||
# open(output_file, 'w', encoding='utf-8').close()
|
||||
|
||||
print("Starting the full-reference image quality assessment pipeline...")
|
||||
compute(reference_dir, distorted_dir, output_file)
|
||||
print("Pipeline finished.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
'''
|
||||
Filename: compute_analytics_and_mos.py
|
||||
Path: /home/netoa/Desktop/ISR
|
||||
Created Date: Tuesday January 7th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Wed Mar 12 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
from metrics.subjective import pre_processing
|
||||
from metrics.subjective import post_processing
|
||||
from metrics.subjective import compute_mos
|
||||
|
||||
# pylint: disable=C0301
|
||||
|
||||
def main():
|
||||
""" Compute subjective metrics. """
|
||||
|
||||
pre_processing.main()
|
||||
post_processing.main()
|
||||
|
||||
compute_mos.main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
'''
|
||||
Filename: evaluation.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
|
||||
'''
|
||||
|
||||
from sklearn.model_selection import cross_val_predict, KFold
|
||||
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
|
||||
def evaluate_model_cv(model, x, y, cv=5):
|
||||
"""Evaluate model with cross-validation and return metrics."""
|
||||
kf = KFold(n_splits=cv, shuffle=True, random_state=42)
|
||||
y_pred = cross_val_predict(model, x, y, cv=kf)
|
||||
|
||||
plcc, _ = pearsonr(y, y_pred)
|
||||
srcc, _ = spearmanr(y, y_pred)
|
||||
mse = mean_squared_error(y, y_pred)
|
||||
mae = mean_absolute_error(y, y_pred)
|
||||
|
||||
return {
|
||||
"PLCC": round(plcc, 4),
|
||||
"SRCC": round(srcc, 4),
|
||||
"MSE": round(mse, 4),
|
||||
"MAE": round(mae, 4)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
'''
|
||||
Filename: models.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
|
||||
'''
|
||||
|
||||
from sklearn.linear_model import LinearRegression, Ridge
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
from sklearn.svm import SVR
|
||||
|
||||
|
||||
def get_models():
|
||||
"""Return dictionary of regression models for fusion pipeline."""
|
||||
|
||||
models = {
|
||||
"LinearRegression": LinearRegression(),
|
||||
"Ridge": Ridge(alpha=1.0),
|
||||
"RandomForest": RandomForestRegressor(n_estimators=200, max_depth=None, random_state=42),
|
||||
"SVR": SVR(kernel="rbf")
|
||||
}
|
||||
|
||||
# Optional: XGBoost
|
||||
try:
|
||||
from xgboost import XGBRegressor
|
||||
models["XGBoost"] = XGBRegressor(
|
||||
n_estimators=200,
|
||||
max_depth=None,
|
||||
learning_rate=0.05,
|
||||
reg_alpha=0.1,
|
||||
reg_lambda=0.1,
|
||||
subsample=0.8,
|
||||
colsample_bytree=0.8,
|
||||
random_state=42
|
||||
)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Optional: LightGBM
|
||||
try:
|
||||
from lightgbm import LGBMRegressor
|
||||
models["LightGBM"] = LGBMRegressor(
|
||||
n_estimators=200,
|
||||
max_depth=None,
|
||||
learning_rate=0.05,
|
||||
reg_alpha=0.1,
|
||||
reg_lambda=0.1,
|
||||
subsample=0.8,
|
||||
colsample_bytree=0.8,
|
||||
random_state=42
|
||||
)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
return models
|
||||
@@ -0,0 +1,37 @@
|
||||
'''
|
||||
Filename: plotting.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 matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
|
||||
def plot_fusion_result(y_true, y_pred, model_name, output_dir):
|
||||
"""Scatter plot: MOS vs predicted fused score."""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
plt.figure(figsize=(6, 6))
|
||||
sns.scatterplot(x=y_pred, y=y_true, alpha=0.6, color="blue")
|
||||
z = np.polyfit(y_pred, y_true, 1)
|
||||
p = np.poly1d(z)
|
||||
plt.plot(y_pred, p(y_pred), color="red", linewidth=2)
|
||||
|
||||
plt.xlabel("Predicted Fused Score")
|
||||
plt.ylabel("MOS")
|
||||
plt.title(f"MOS vs Predicted ({model_name})")
|
||||
plt.grid(True, linestyle="--", alpha=0.5)
|
||||
plt.tight_layout()
|
||||
|
||||
plt.savefig(os.path.join(output_dir, f"fusion_plot_{model_name}.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, f"fusion_plot_{model_name}.eps"), dpi=300)
|
||||
|
||||
plt.close()
|
||||
@@ -0,0 +1,20 @@
|
||||
'''
|
||||
Filename: utils.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
|
||||
|
||||
def save_fused_scores(predictions, filenames, output_path):
|
||||
"""Save fused quality scores with associated filenames to CSV."""
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
df = pd.DataFrame({"file_name": filenames, "fused_score": predictions})
|
||||
df.to_csv(output_path, index=False)
|
||||
@@ -0,0 +1,80 @@
|
||||
'''
|
||||
Filename: evaluation.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts/nr_fusion
|
||||
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 matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
|
||||
def evaluate_and_plot(y_true, y_pred, output_dir, show_trend=True):
|
||||
"""
|
||||
Compute evaluation metrics and generate scatter plot.
|
||||
|
||||
Args:
|
||||
y_true (array-like): Ground truth pseudo-MOS values.
|
||||
y_pred (array-like): Predicted pseudo-MOS values.
|
||||
output_dir (str): Directory to save plots.
|
||||
show_trend (bool): Whether to include a fitted trendline.
|
||||
"""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# Plot
|
||||
plt.figure(figsize=(7, 7))
|
||||
plt.scatter(y_true, y_pred, alpha=0.6, color="darkorange", s=20)
|
||||
|
||||
# Diagonal reference
|
||||
min_val = min(min(y_true), min(y_pred))
|
||||
max_val = max(max(y_true), max(y_pred))
|
||||
plt.plot([min_val, max_val], [min_val, max_val], '--', color="gray", alpha=0.7)
|
||||
|
||||
# Optional trendline
|
||||
if show_trend:
|
||||
z = np.polyfit(y_true, y_pred, 1)
|
||||
p = np.poly1d(z)
|
||||
plt.plot(y_true, p(y_true), color="blue", linewidth=1.5, label="Trendline")
|
||||
plt.legend()
|
||||
|
||||
plt.xlabel("Fusion_RF (pseudo-MOS)")
|
||||
plt.ylabel("NR Prediction")
|
||||
plt.title("NR IQA Prediction vs. Fusion_RF")
|
||||
plt.grid(True, linestyle="--", alpha=0.4)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(output_dir, "nr_vs_fusion_rf.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, "nr_vs_fusion_rf.eps"), dpi=300)
|
||||
|
||||
plt.close()
|
||||
|
||||
|
||||
def compute_correlation_scores(y_true, y_pred):
|
||||
"""
|
||||
Compute correlation scores between ground truth and predicted values.
|
||||
|
||||
Args:
|
||||
y_true (array-like): Ground truth pseudo-MOS scores.
|
||||
y_pred (array-like): Predicted scores from NR IQA model.
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with PLCC and SRCC scores.
|
||||
"""
|
||||
|
||||
# Compute metrics
|
||||
mse = mean_squared_error(y_true, y_pred)
|
||||
mae = mean_absolute_error(y_true, y_pred)
|
||||
plcc, _ = pearsonr(y_true, y_pred)
|
||||
srcc, _ = spearmanr(y_true, y_pred)
|
||||
|
||||
return {"PLCC": plcc,
|
||||
"SRCC": srcc,
|
||||
"MSE": mse,
|
||||
"MAE": mae}
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
Feature extraction for No-Reference IQA using deep facial feature embeddings.
|
||||
"""
|
||||
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchvision import models
|
||||
from torchvision import transforms
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
from facenet_pytorch import InceptionResnetV1
|
||||
|
||||
|
||||
def extract_features(df, image_dir, encoder="resnet"):
|
||||
""" Extract deep features from distorted images using a selected encoder. """
|
||||
|
||||
if encoder == "resnet":
|
||||
return extract_resnet_features(df, image_dir)
|
||||
elif encoder == "facenet":
|
||||
return extract_facenet_features(df, image_dir)
|
||||
else:
|
||||
raise ValueError(f"Invalid encoder: {encoder}.")
|
||||
|
||||
|
||||
def extract_facenet_features(df, image_dir):
|
||||
""" Extract deep features from distorted images using a face embedding network (FaceNet). """
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
model = InceptionResnetV1(pretrained='vggface2').eval().to(device)
|
||||
|
||||
preprocess = transforms.Compose([
|
||||
transforms.Resize((160, 160)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize([0.5], [0.5])
|
||||
])
|
||||
|
||||
features = []
|
||||
labels = []
|
||||
filenames = []
|
||||
|
||||
for _, row in tqdm(df.iterrows(), total=len(df), desc="Extracting FaceNet features"):
|
||||
fname = row["file_name"]
|
||||
img_path = os.path.join(image_dir, f'{fname}.jpg')
|
||||
if not os.path.exists(img_path):
|
||||
print(f"[WARN] File not found: {img_path}")
|
||||
continue
|
||||
|
||||
try:
|
||||
img = Image.open(img_path).convert("RGB")
|
||||
input_tensor = preprocess(img).unsqueeze(0).to(device)
|
||||
with torch.no_grad():
|
||||
embedding = model(input_tensor).cpu().numpy().flatten()
|
||||
|
||||
if np.isnan(embedding).any():
|
||||
raise ValueError("Embedding contains NaN")
|
||||
|
||||
features.append(embedding)
|
||||
labels.append(row["fusion_rf"])
|
||||
filenames.append(fname)
|
||||
except (FileNotFoundError, ValueError, OSError) as e:
|
||||
print(f"[WARN] Skipping {fname}: {e}")
|
||||
|
||||
if len(features) == 0:
|
||||
raise RuntimeError("No features extracted. Check image paths or model setup.")
|
||||
|
||||
x = np.array(features)
|
||||
y = np.array(labels)
|
||||
return x, y, filenames
|
||||
|
||||
|
||||
def extract_resnet_features(df, image_dir):
|
||||
""" Extract ResNet features from distorted images. """
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
model = models.resnet18(pretrained=True)
|
||||
model.fc = nn.Identity() # Remove final classification layer
|
||||
model.eval().to(device)
|
||||
|
||||
preprocess = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
features, labels, filenames = [], [], []
|
||||
|
||||
for _, row in tqdm(df.iterrows(), total=len(df), desc="Extracting ResNet features"):
|
||||
fname = row["file_name"]
|
||||
img_path = os.path.join(image_dir, f'{fname}.jpg')
|
||||
if not os.path.exists(img_path):
|
||||
print(f"[WARN] File not found: {img_path}")
|
||||
continue
|
||||
|
||||
try:
|
||||
img = Image.open(img_path).convert("RGB")
|
||||
input_tensor = preprocess(img).unsqueeze(0).to(device)
|
||||
with torch.no_grad():
|
||||
embedding = model(input_tensor).cpu().numpy().flatten()
|
||||
|
||||
if np.isnan(embedding).any():
|
||||
raise ValueError("Embedding contains NaN")
|
||||
|
||||
features.append(embedding)
|
||||
labels.append(row["fusion_rf"])
|
||||
filenames.append(fname)
|
||||
except (FileNotFoundError, ValueError, OSError) as e:
|
||||
print(f"[WARN] Skipping {fname}: {e}")
|
||||
|
||||
if len(features) == 0:
|
||||
raise RuntimeError("No features extracted. Check image paths or model setup.")
|
||||
|
||||
return np.array(features), np.array(labels), filenames
|
||||
@@ -0,0 +1,40 @@
|
||||
'''
|
||||
Filename: models.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts/nr_fusion
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Mon Mar 24 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
from sklearn.model_selection import cross_val_predict
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
def train_regressor(x, y):
|
||||
"""
|
||||
Train and cross-validate a RandomForest regressor.
|
||||
|
||||
Args:
|
||||
X (np.ndarray): Feature matrix.
|
||||
y (np.ndarray): Target values (pseudo-MOS).
|
||||
|
||||
Returns:
|
||||
y_pred (np.ndarray): Cross-validated predictions.
|
||||
model (Regressor): Trained RandomForest model.
|
||||
scaler (StandardScaler): Feature normalizer.
|
||||
"""
|
||||
scaler = StandardScaler()
|
||||
x_scaled = scaler.fit_transform(x)
|
||||
|
||||
model = RandomForestRegressor(n_estimators=100, random_state=42)
|
||||
y_pred = cross_val_predict(model, x_scaled, y, cv=5)
|
||||
|
||||
model.fit(x_scaled, y)
|
||||
|
||||
return y_pred, model, scaler
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
Fusion Pipeline Script
|
||||
|
||||
This module runs a full regression-based fusion process:
|
||||
1. Selects top-k IQA metrics based on PLCC.
|
||||
2. Normalizes the selected features.
|
||||
3. Trains multiple regression models (linear and nonlinear).
|
||||
4. Evaluates each model using cross-validation.
|
||||
5. Saves predicted fused scores and visualization plots.
|
||||
6. Applies trained model to all available images and saves full prediction CSV.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
from fr_fusion.models import get_models
|
||||
from fr_fusion.evaluation import evaluate_model_cv
|
||||
from fr_fusion.plotting import plot_fusion_result
|
||||
from fr_fusion.utils import save_fused_scores
|
||||
|
||||
def plot_rf_feature_importance(top_metrics, x_scaled, y, output_dir):
|
||||
"""Plot feature importances from Random Forest regressor."""
|
||||
|
||||
|
||||
rf = RandomForestRegressor(n_estimators=100, random_state=42)
|
||||
rf.fit(x_scaled, y)
|
||||
importances = rf.feature_importances_
|
||||
|
||||
feature_importance_df = pd.DataFrame({
|
||||
"Metric": top_metrics,
|
||||
"Importance": importances
|
||||
}).sort_values(by="Importance", ascending=False)
|
||||
|
||||
plt.figure(figsize=(8, 5))
|
||||
plt.barh(feature_importance_df["Metric"], feature_importance_df["Importance"], color="darkgreen")
|
||||
plt.xlabel("Feature Importance")
|
||||
plt.ylabel("FR-IQA Metrics")
|
||||
plt.title("Random Forest Feature Importances")
|
||||
plt.gca().invert_yaxis()
|
||||
plt.grid(axis="x", linestyle="--", alpha=0.6)
|
||||
plt.tight_layout()
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.savefig(os.path.join(output_dir, "ffr_rf_feature_importance.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, "ffr_rf_feature_importance.eps"), dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
|
||||
def plot_model_comparison(score_dict, output_dir):
|
||||
"""Generate individual subplots for each metric to compare models."""
|
||||
df = pd.DataFrame(score_dict).T
|
||||
|
||||
_, axes = plt.subplots(2, 2, figsize=(14, 10))
|
||||
axes = axes.flatten()
|
||||
|
||||
metrics = ["PLCC", "SRCC", "MSE", "MAE"]
|
||||
colors = ["steelblue", "darkorange", "indianred", "seagreen"]
|
||||
|
||||
for i, metric in enumerate(metrics):
|
||||
df[metric].sort_values(ascending=metric in ["MSE", "MAE"]).plot.bar(
|
||||
ax=axes[i], color=colors[i])
|
||||
axes[i].set_title(f"{metric} Comparison Across Models")
|
||||
axes[i].set_ylabel(metric)
|
||||
axes[i].set_xlabel("Model")
|
||||
axes[i].tick_params(axis='x', rotation=45)
|
||||
axes[i].grid(axis="y", linestyle="--", alpha=0.5)
|
||||
|
||||
best_idx = df[metric].idxmax() if metric in ["PLCC", "SRCC"] else df[metric].idxmin()
|
||||
axes[i].annotate("Best", xy=(list(df.index).index(best_idx), df[metric][best_idx]),
|
||||
xytext=(0, 5), textcoords="offset points",
|
||||
ha='center', va='bottom', fontsize=9, color='green', weight='bold')
|
||||
|
||||
plt.tight_layout()
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.savefig(os.path.join(output_dir, "model_comparison.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, "model_comparison.eps"), dpi=300)
|
||||
|
||||
plt.close()
|
||||
|
||||
def run_fusion_pipeline(merged_df: pd.DataFrame, results_df: pd.DataFrame, top_k: int = 5,
|
||||
output_dir: str = "results/ffr_metric") -> None:
|
||||
"""
|
||||
Run fusion pipeline with different regressors using top-k ranked IQA metrics.
|
||||
"""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# 1. Select top-k metrics by PLCC
|
||||
selected_metrics = results_df.head(top_k).index.tolist()
|
||||
x = merged_df[selected_metrics]
|
||||
y = merged_df["mos"]
|
||||
filenames = merged_df["file_name"]
|
||||
|
||||
# 2. Normalize features
|
||||
scaler = StandardScaler()
|
||||
x_scaled = pd.DataFrame(scaler.fit_transform(x), columns=x.columns)
|
||||
|
||||
# 3. Train and evaluate models
|
||||
models = get_models()
|
||||
score_summary = {}
|
||||
|
||||
for name, model in models.items():
|
||||
print(f"\nRunning model: {name}")
|
||||
scores = evaluate_model_cv(model, x_scaled, y, cv=5)
|
||||
print(f"Scores: {scores}")
|
||||
score_summary[name] = scores
|
||||
|
||||
model.fit(x_scaled, y)
|
||||
y_pred = model.predict(x_scaled)
|
||||
|
||||
score_path = os.path.join(output_dir, f"fused_scores_{name}.csv")
|
||||
save_fused_scores(y_pred, filenames, score_path)
|
||||
plot_fusion_result(y, y_pred, name, output_dir)
|
||||
|
||||
# If RandomForest, apply to all available data
|
||||
if name == "RandomForest":
|
||||
print("\nApplying LinearRegression to full objective dataset...")
|
||||
full_df = pd.read_csv("results/sheets/iqa_objective.csv")
|
||||
if not all(metric in full_df.columns for metric in selected_metrics):
|
||||
print("Some metrics missing in full objective data. Skipping.")
|
||||
continue
|
||||
|
||||
x_all = full_df[selected_metrics]
|
||||
x_all_scaled = scaler.transform(x_all)
|
||||
y_all_pred = model.predict(x_all_scaled)
|
||||
|
||||
full_df["fusion_rf"] = y_all_pred
|
||||
fusion_df = full_df[["file_name", "fusion_rf"]]
|
||||
fusion_df.to_csv(os.path.join(output_dir, "fusion_scores_all.csv"), index=False)
|
||||
print(f"Saved full fusion scores to {output_dir}/fusion_scores_all.csv")
|
||||
|
||||
# 4. Generate comparison plot
|
||||
plot_model_comparison(score_summary, output_dir)
|
||||
|
||||
# 5. Save all model scores to CSV
|
||||
score_summary_df = pd.DataFrame(score_summary)
|
||||
score_summary_df.index.name = "Model"
|
||||
score_summary_df.to_csv(os.path.join(output_dir, "model_scores.csv"))
|
||||
print(f"\nSaved model evaluation scores to {output_dir}/model_scores.csv")
|
||||
|
||||
# 6. Plot Random Forest feature importances using top-5 metrics
|
||||
plot_rf_feature_importance(selected_metrics, x_scaled, y, output_dir)
|
||||
|
||||
print("\nFusion pipeline completed.")
|
||||
|
||||
|
||||
def compute_ranking(merged_df):
|
||||
""" Compute PLCC and SRCC rankings for each IQA metric. """
|
||||
|
||||
metrics = merged_df.drop(columns=["file_name", "mos"])
|
||||
plcc, srcc = {}, {}
|
||||
for metric in metrics.columns:
|
||||
plcc[metric], _ = pearsonr(merged_df[metric], merged_df["mos"])
|
||||
srcc[metric], _ = spearmanr(merged_df[metric], merged_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 main():
|
||||
""" Main function to run the fusion pipeline with top-k ranked IQA metrics. """
|
||||
# Input paths
|
||||
objective_path = "results/sheets/iqa_objective.csv"
|
||||
subjective_path = "results/sheets/iqa_subjective.csv"
|
||||
|
||||
# Load and merge data
|
||||
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")
|
||||
|
||||
# Compute PLCC/SRCC rankings
|
||||
results_df = compute_ranking(merged_df)
|
||||
|
||||
# Run fusion
|
||||
run_fusion_pipeline(merged_df, results_df, top_k=5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
Pseudo-MOS Learning Script: No-Reference IQA Regression from Fused Full-Reference Scores
|
||||
|
||||
This script trains a no-reference IQA regressor using pseudo-MOS (fusion_rf scores)
|
||||
generated by a full-reference fusion model.
|
||||
|
||||
Steps:
|
||||
1. Load distorted image paths and corresponding fusion scores.
|
||||
2. Extract deep features using selected encoder.
|
||||
3. Train regression models to predict fusion_rf scores.
|
||||
4. Evaluate using cross-validation.
|
||||
5. Save predictions and comparison plots.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
|
||||
from nr_fusion.features import extract_features
|
||||
from nr_fusion.models import train_regressor
|
||||
from nr_fusion.evaluation import evaluate_and_plot, compute_correlation_scores
|
||||
|
||||
def main(encoder: str):
|
||||
"""Run no-reference IQA regression using selected encoder."""
|
||||
# Paths
|
||||
image_dir = "images/distorted"
|
||||
scores_csv = "results/ffr_metric/fusion_scores_all.csv"
|
||||
output_dir = f"results/nr_metric/{encoder}"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
pred_csv = os.path.join(output_dir, "nr_predictions.csv")
|
||||
|
||||
# Load fusion scores
|
||||
df = pd.read_csv(scores_csv)
|
||||
if "fusion_rf" not in df.columns:
|
||||
raise ValueError("Column 'fusion_rf' not found in CSV. Run fusion first.")
|
||||
|
||||
# Check if predictions already exist
|
||||
if os.path.exists(pred_csv):
|
||||
print("Predictions already exist. Loading...")
|
||||
pred_df = pd.read_csv(pred_csv)
|
||||
y = pred_df["pseudo_mos"].values
|
||||
y_pred = pred_df["predicted"].values
|
||||
else:
|
||||
# Feature extraction
|
||||
x, y, filenames = extract_features(df, image_dir)
|
||||
|
||||
# Train + cross-validate + predict
|
||||
y_pred, _, _ = train_regressor(x, y)
|
||||
|
||||
# Save predictions
|
||||
pred_df = pd.DataFrame({
|
||||
"file_name": filenames,
|
||||
"pseudo_mos": y,
|
||||
"predicted": y_pred
|
||||
})
|
||||
pred_df.to_csv(os.path.join(output_dir, "nr_predictions.csv"), index=False)
|
||||
|
||||
# Plot results
|
||||
evaluate_and_plot(y, y_pred, output_dir, show_trend=True)
|
||||
|
||||
correlation_scores = compute_correlation_scores(y, y_pred)
|
||||
print("Correlation scores:", correlation_scores)
|
||||
with open(os.path.join(output_dir, "correlation_scores.txt"), "w", encoding="utf-8") as f:
|
||||
for k, v in correlation_scores.items():
|
||||
f.write(f"{k}: {v:.4f}\n")
|
||||
|
||||
print(f"Pseudo-MOS training with {encoder} completed. Predictions saved.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# "resnet"
|
||||
# "facenet"
|
||||
|
||||
main(encoder="resnet")
|
||||
Reference in New Issue
Block a user