417 lines
14 KiB
Python
417 lines
14 KiB
Python
'''
|
|
Filename: pipeline_norefernce.py
|
|
Path: /home/netoa/Desktop/ISR/scripts
|
|
Created Date: Friday May 16th 2025
|
|
Author: Andre Neto
|
|
-----
|
|
Last Modified: Fri May 23 2025
|
|
Modified By: Andre Neto
|
|
-----
|
|
Copyright (c) 2025 Institute of Systems and Robotics
|
|
'''
|
|
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn as nn
|
|
import torch.optim as optim
|
|
from tqdm import tqdm
|
|
import pandas as pd
|
|
from torch.utils.data import Dataset, DataLoader
|
|
from torchvision import transforms
|
|
from PIL import Image
|
|
|
|
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
|
from scipy.stats import pearsonr, spearmanr
|
|
|
|
from torchinfo import summary
|
|
import torchvision.models as models
|
|
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sns
|
|
|
|
# pylint: disable=line-too-long
|
|
|
|
|
|
class NoReferenceModel:
|
|
"""
|
|
A class for training a no-reference image quality assessment (NR-IQA) model
|
|
using pseudo mean opinion scores (MOS) and evaluating it on a test set.
|
|
"""
|
|
|
|
|
|
def __init__(self, pseudo_mos_csv, k, train_dirs, test_dir, output_dir):
|
|
"""
|
|
Initialize the NR-IQA model with paths to training and evaluation data.
|
|
|
|
Args:
|
|
pseudo_mos_csv (str or Path): Path to the CSV file containing pseudo-MOS labels.
|
|
train_dirs (List[str or Path]): List of directories with images for training.
|
|
test_dir (str or Path): Directory containing the test images and mos.csv.
|
|
output_dir (str or Path): Path to save model cp, pred, and evaluation results.
|
|
"""
|
|
|
|
self.pseudo_mos_csv = Path(pseudo_mos_csv)
|
|
self.train_dirs = [Path(d) for d in train_dirs]
|
|
self.test_dir = Path(test_dir)
|
|
self.output_dir = Path(output_dir)
|
|
self.output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
self.batch_size = 16
|
|
self.num_workers = 4
|
|
self.train_loader = None
|
|
self.test_loader = None
|
|
self.test_mos = None
|
|
self.model = None
|
|
|
|
|
|
def load_data(self):
|
|
"""
|
|
Load and preprocess the training and testing data.
|
|
|
|
This method:
|
|
- Loads image paths and scores (both pseudo and real) from training directories
|
|
- Loads test images and their real MOS scores
|
|
- Applies transformations (resize, normalization)
|
|
- Constructs PyTorch DataLoaders for both sets
|
|
"""
|
|
print("Loading training and testing data...")
|
|
|
|
transform = transforms.Compose([
|
|
transforms.Resize((224, 224)),
|
|
transforms.ToTensor(),
|
|
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
|
std=[0.229, 0.224, 0.225])
|
|
])
|
|
|
|
# Load pseudo-MOS CSV
|
|
df_pseudo = pd.read_csv(self.pseudo_mos_csv)
|
|
pseudo_dict = dict(zip(df_pseudo["file_name"], df_pseudo["pseudo_mos"]))
|
|
|
|
# Load true MOS if available (from labeled/train)
|
|
labeled_train_mos_path = Path("data/labeled/train/mos_debiased.csv")
|
|
if labeled_train_mos_path.exists():
|
|
df_true = pd.read_csv(labeled_train_mos_path)
|
|
pseudo_dict.update(dict(zip(df_true["file_name"], df_true["mos"])))
|
|
print(f"- Loaded {len(df_true)} true MOS entries from labeled/train")
|
|
|
|
# Combine training images from all dirs
|
|
train_samples = []
|
|
for train_dir in self.train_dirs:
|
|
for image_path in Path(train_dir).glob("*.jpg"):
|
|
fname = image_path.name
|
|
if fname in pseudo_dict:
|
|
train_samples.append((image_path, pseudo_dict[fname]))
|
|
|
|
self.train_loader = DataLoader(
|
|
MOSDataset(train_samples, transform),
|
|
batch_size=self.batch_size,
|
|
shuffle=True,
|
|
num_workers=self.num_workers
|
|
)
|
|
|
|
# Load test MOS
|
|
df_test = pd.read_csv(self.test_dir / "mos_debiased.csv")
|
|
test_dict = dict(zip(df_test["file_name"], df_test["mos"]))
|
|
|
|
test_samples = []
|
|
for image_path in (self.test_dir).glob("*.jpg"):
|
|
fname = image_path.name
|
|
if fname in test_dict:
|
|
test_samples.append((image_path, test_dict[fname]))
|
|
|
|
self.test_mos = [s[1] for s in test_samples]
|
|
self.test_loader = DataLoader(
|
|
MOSDataset(test_samples, transform),
|
|
batch_size=self.batch_size,
|
|
shuffle=False,
|
|
num_workers=self.num_workers
|
|
)
|
|
|
|
print(f"- Loaded {len(train_samples)} total training samples (pseudo + real)")
|
|
print(f"- Loaded {len(test_samples)} test samples")
|
|
print(f"Files in mos_debiased: {len(df_test)}")
|
|
print(f"Matching image files: {len(test_samples)}")
|
|
|
|
|
|
def build_model(self):
|
|
"""
|
|
Build and initialize the CNN-based NR-IQA model.
|
|
|
|
The model consists of:
|
|
- A ResNet18 backbone pretrained on ImageNet
|
|
- A fully connected regression head (MLP) that predicts a continuous MOS value
|
|
|
|
All layers are trainable (fine-tuning enabled).
|
|
The model is moved to the appropriate device (GPU or CPU).
|
|
"""
|
|
print("Building ResNet18-based NR-IQA model...")
|
|
|
|
# Load pretrained ResNet18
|
|
resnet = models.resnet18(pretrained=True)
|
|
|
|
# Replace the final layer with an MLP regressor
|
|
resnet.fc = nn.Sequential(
|
|
nn.Linear(512, 256),
|
|
nn.ReLU(),
|
|
nn.Dropout(0.4),
|
|
nn.Linear(256, 1)
|
|
)
|
|
|
|
self.model = resnet.to(self.device)
|
|
|
|
# Print model summary
|
|
print("Model summary:")
|
|
summary(self.model, input_size=(1, 3, 1350, 1350), device=str(self.device))
|
|
|
|
print(f"- Model ready on device: {self.device}")
|
|
|
|
|
|
def load_model(self):
|
|
"""
|
|
Loads the saved model weights into a new instance of the model.
|
|
Assumes the model architecture is the same as the one used during training.
|
|
"""
|
|
print("Loading model from checkpoint...")
|
|
|
|
self.build_model() # Rebuild architecture
|
|
model_path = self.output_dir / "model.pth"
|
|
self.model.load_state_dict(torch.load(model_path, map_location=self.device))
|
|
self.model.eval()
|
|
print(f"Model loaded from: {model_path}")
|
|
|
|
|
|
def train(self, n_epochs=30, lr=1e-4):
|
|
"""
|
|
Train the NR-IQA model using the combined training dataset.
|
|
|
|
This method performs standard supervised training using MSE loss and Adam optimizer.
|
|
After training, the final model is saved to disk, along with a CSV containing the
|
|
training loss per epoch.
|
|
|
|
Args:
|
|
n_epochs (int): Number of training epochs.
|
|
lr (float): Learning rate for the optimizer.
|
|
"""
|
|
print("Starting training...")
|
|
|
|
self.model.train()
|
|
|
|
criterion = nn.MSELoss()
|
|
optimizer = optim.Adam(self.model.parameters(), lr=lr)
|
|
|
|
history = []
|
|
|
|
for epoch in range(n_epochs):
|
|
running_loss = 0.0
|
|
for images, targets, _ in tqdm(self.train_loader, desc=f"Epoch {epoch+1}/{n_epochs}"):
|
|
images = images.to(self.device)
|
|
targets = targets.to(self.device).unsqueeze(1)
|
|
|
|
optimizer.zero_grad()
|
|
outputs = self.model(images)
|
|
loss = criterion(outputs, targets)
|
|
loss.backward()
|
|
optimizer.step()
|
|
|
|
running_loss += loss.item() * images.size(0)
|
|
|
|
epoch_loss = running_loss / len(self.train_loader.dataset)
|
|
history.append({"epoch": epoch+1, "loss": epoch_loss})
|
|
print(f"Epoch {epoch+1}/{n_epochs} - Loss: {epoch_loss:.4f}")
|
|
|
|
# Save model and training loss history
|
|
model_path = self.output_dir / "model.pth"
|
|
torch.save(self.model.state_dict(), model_path)
|
|
print(f"Model saved to: {model_path}")
|
|
|
|
loss_df = pd.DataFrame(history)
|
|
loss_df.to_csv(self.output_dir / "train_loss.csv", index=False)
|
|
print(f"Training loss saved to: {self.output_dir / 'train_loss.csv'}")
|
|
|
|
|
|
def plot_predictions(self, pred_df: pd.DataFrame, output_path: Path):
|
|
"""
|
|
Generates and saves a scatter plot of predicted vs real MOS.
|
|
"""
|
|
|
|
plt.rcParams.update({"font.size": 16})
|
|
|
|
plt.figure(figsize=(7, 5))
|
|
|
|
plt.xlim(0, 100)
|
|
plt.ylim(0, 100)
|
|
sns.scatterplot(x="mos", y="predicted", data=pred_df, alpha=0.7)
|
|
sns.regplot(x="mos", y="predicted", data=pred_df, scatter=False, color="red", label="Linear fit")
|
|
|
|
# Ideal 1:1 trend line
|
|
plt.plot([0, 100], [0, 100], 'k--', label="y = x", color="gray")
|
|
|
|
# MOS test set
|
|
# NR train set
|
|
plt.title("pMOS-FRLL Predictions vs NR train set")
|
|
|
|
# Ground-truth MOS
|
|
# Pseudo-MOS & Ground-truth MOS
|
|
plt.xlabel("Pseudo-MOS & Ground-truth MOS")
|
|
plt.ylabel("Predicted MOS")
|
|
plt.legend()
|
|
plt.grid(True)
|
|
plt.tight_layout()
|
|
|
|
plot_file = output_path / "predictions_train.pdf"
|
|
|
|
plt.savefig(plot_file, dpi=300)
|
|
plt.close()
|
|
print(f"- Prediction plot saved to: {plot_file}")
|
|
|
|
|
|
def evaluate(self):
|
|
"""
|
|
Evaluate the trained model on the labeled/test set with real MOS values.
|
|
|
|
This method:
|
|
- Performs inference on the test set
|
|
- Computes PLCC, SRCC, MSE, and MAE between predicted and real MOS
|
|
- Saves predictions and metrics to disk
|
|
"""
|
|
print("Evaluating model on test set...")
|
|
|
|
self.model.eval()
|
|
preds = []
|
|
fnames = []
|
|
|
|
with torch.no_grad():
|
|
for images, _, filenames in self.test_loader:
|
|
images = images.to(self.device)
|
|
outputs = self.model(images).squeeze(1).cpu().numpy()
|
|
preds.extend(outputs)
|
|
fnames.extend(filenames)
|
|
|
|
y_true = np.array(self.test_mos)
|
|
y_pred = np.array(preds)
|
|
|
|
# Compute metrics
|
|
plcc, _ = pearsonr(y_true, y_pred)
|
|
srcc, _ = spearmanr(y_true, y_pred)
|
|
mse = mean_squared_error(y_true, y_pred)
|
|
mae = mean_absolute_error(y_true, y_pred)
|
|
|
|
print(f" PLCC = {plcc:.4f} | SRCC = {srcc:.4f} | MSE = {mse:.4f} | MAE = {mae:.4f}")
|
|
|
|
# Save predictions
|
|
pred_df = pd.DataFrame({
|
|
"file_name": fnames,
|
|
"predicted": y_pred,
|
|
"mos": y_true
|
|
})
|
|
pred_path = self.output_dir / "predictions.csv"
|
|
pred_df.to_csv(pred_path, index=False)
|
|
print(f"- Predictions saved to: {pred_path}")
|
|
|
|
# Save metrics
|
|
metrics_df = pd.DataFrame([{
|
|
"PLCC": plcc,
|
|
"SRCC": srcc,
|
|
"MSE": mse,
|
|
"MAE": mae
|
|
}])
|
|
metrics_df.to_csv(self.output_dir / "metrics.csv", index=False)
|
|
print(f"- Metrics saved to: {self.output_dir / 'metrics.csv'}")
|
|
|
|
# Plot results
|
|
self.plot_predictions(pred_df, self.output_dir)
|
|
|
|
|
|
def run(self, n_epochs=30, lr=1e-4):
|
|
"""
|
|
Execute the full NR-IQA training and evaluation pipeline.
|
|
|
|
This method performs:
|
|
1. Loading of training and test data (MOS and pseudo-MOS)
|
|
2. Building the CNN regression model (ResNet18 + MLP)
|
|
3. Training on the combined labeled/distorted set
|
|
4. Evaluation on the disjoint labeled/test set
|
|
5. Saving predictions and evaluation metrics
|
|
"""
|
|
self.load_data()
|
|
self.build_model()
|
|
self.train(n_epochs=n_epochs, lr=lr)
|
|
self.evaluate()
|
|
|
|
|
|
|
|
class MOSDataset(Dataset):
|
|
"""
|
|
PyTorch Dataset for IQA images with pseudo or real MOS labels.
|
|
|
|
This dataset supports loading from multiple sources (distorted, labeled/train),
|
|
and makes no distinction between pseudo and real scores. It simply associates
|
|
each image with its corresponding score and applies the required transformation.
|
|
|
|
Attributes:
|
|
samples (List[Tuple[Path, float]]): List of image paths paired with MOS/pseudo-MOS scores.
|
|
transform (Callable): Transformation function to apply to the image.
|
|
"""
|
|
|
|
|
|
def __init__(self, samples, transform=None):
|
|
"""
|
|
Initialize the dataset with image-score pairs.
|
|
|
|
Args:
|
|
samples (List[Tuple[Path, float]]): List of (image_path, score).
|
|
transform (Callable, optional): Transformations to apply to the image.
|
|
"""
|
|
self.samples = samples
|
|
self.transform = transform
|
|
|
|
|
|
def __len__(self):
|
|
"""Return the number of samples in the dataset."""
|
|
return len(self.samples)
|
|
|
|
|
|
def __getitem__(self, idx):
|
|
"""
|
|
Load image and corresponding score at index idx.
|
|
|
|
Returns:
|
|
Tuple[Tensor, Tensor, str]: image tensor, score tensor, file name
|
|
"""
|
|
path, score = self.samples[idx]
|
|
image = Image.open(path).convert("RGB")
|
|
if self.transform:
|
|
image = self.transform(image)
|
|
return image, torch.tensor(score, dtype=torch.float32), path.name
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
k = 6
|
|
|
|
model = NoReferenceModel(
|
|
pseudo_mos_csv=f"results/pipeline_fusion/k{k}/pseudo_mos.csv",
|
|
k = k,
|
|
train_dirs=["data/labeled/train", "data/distorted"],
|
|
test_dir="data/labeled/train",
|
|
output_dir=f"results/pipeline_noreference/k{k}"
|
|
)
|
|
|
|
model.load_data()
|
|
model_file = model.output_dir / "model.pth"
|
|
|
|
if model_file.exists():
|
|
print("Model already trained, loading from checkpoint.")
|
|
model.load_model()
|
|
model.evaluate()
|
|
else:
|
|
print("Training model from scratch...")
|
|
model.build_model()
|
|
model.train(n_epochs=30, lr=1e-4)
|
|
model.evaluate()
|