Files
iqa-study/scripts/nr_fusion/features.py
T
2025-04-12 03:19:13 +01:00

116 lines
3.8 KiB
Python

"""
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