Initial clean commit

This commit is contained in:
Andre Neto
2025-04-12 03:19:13 +01:00
commit 62ff4d6c25
96 changed files with 104109 additions and 0 deletions
View File
+80
View File
@@ -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}
+115
View File
@@ -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
+40
View File
@@ -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