Initial commit: new baseline

This commit is contained in:
Andre Neto
2025-08-31 19:45:56 +01:00
commit 0dcc994dbe
416 changed files with 522730 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
'''
Filename: __init__.py
Path: /home/netoa/Desktop/ISR/metrics
Created Date: Wednesday December 18th 2024
Author: Andre Neto
-----
Last Modified: Wed Dec 18 2024
Modified By: Andre Neto
-----
Copyright (c) 2024 Institute of Systems and Robotics
'''
@@ -0,0 +1,11 @@
'''
Filename: __init__.py
Path: /home/netoa/Desktop/ISR/metrics/fr
Created Date: Wednesday December 18th 2024
Author: Andre Neto
-----
Last Modified: Wed Dec 18 2024
Modified By: Andre Neto
-----
Copyright (c) 2024 Institute of Systems and Robotics
'''
+156
View File
@@ -0,0 +1,156 @@
"""
This module contains functions for computing color-based image quality metrics,
such as C-SSIM (Color SSIM), FSIMc (Color Feature Similarity Index for Color Images),
and VIFc (Color Visual Information Fidelity for Color Images).
It uses structural similarity indices and feature similarity to evaluate the
similarity between reference and distorted color images.
Functions:
- compute_all: Computes all color-based image quality metrics.
- load_color_image: Loads a color image.
- c_ssim: Computes the Color Structural Similarity Index (C-SSIM).
- fsimc: Computes the Feature Similarity Index for Color Images (FSIMc).
- vifc: Computes the Visual Information Fidelity for Color Images (VIFc).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from skimage.color import rgb2yuv # pylint: disable=E0611
from skimage.metrics import structural_similarity # pylint: disable=E0611
from skimage.filters import sobel # pylint: disable=E0611
def compute_all(ref_path, dist_path):
"""
Computes multiple color-based image quality metrics between a reference and a distorted image.
"""
ref_img = load_color_image(ref_path)
dist_img = load_color_image(dist_path)
output = {}
metrics = [
("C-SSIM", lambda: c_ssim(ref_img, dist_img)),
("FSIMc", lambda: fsimc(ref_img, dist_img)),
("VIFc", lambda: vifc(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load color images
def load_color_image(path):
"""
Loads a color image and converts it to floating-point format.
"""
img = io.imread(path)
img = img_as_float(img)
return img
# C-SSIM (Color Structural Similarity Index)
def c_ssim(ref_img, dist_img):
"""
Computes the SSIM (Structural Similarity Index) for color images by averaging the SSIM
across the YUV color channels.
"""
ref_yuv = rgb2yuv(ref_img)
dist_yuv = rgb2yuv(dist_img)
# Compute SSIM for each YUV channel
y_ssim = structural_similarity(ref_yuv[:, :, 0], dist_yuv[:, :, 0], data_range=1.0)
u_ssim = structural_similarity(ref_yuv[:, :, 1], dist_yuv[:, :, 1], data_range=1.0)
v_ssim = structural_similarity(ref_yuv[:, :, 2], dist_yuv[:, :, 2], data_range=1.0)
# Average the SSIM values of the YUV channels
c_ssim_value = (y_ssim + u_ssim + v_ssim) / 3
return c_ssim_value
# FSIMc (Feature Similarity Index for Color Images)
def fsimc(ref_img, dist_img):
"""
Computes FSIM (Feature Similarity Index) for color images by averaging the FSIM
across the YUV color channels.
"""
ref_yuv = rgb2yuv(ref_img)
dist_yuv = rgb2yuv(dist_img)
y_fsim = fsim(ref_yuv[:, :, 0], dist_yuv[:, :, 0])
u_fsim = fsim(ref_yuv[:, :, 1], dist_yuv[:, :, 1])
v_fsim = fsim(ref_yuv[:, :, 2], dist_yuv[:, :, 2])
color_fsim_value = (y_fsim + u_fsim + v_fsim) / 3
return color_fsim_value
# FSIM (Feature Similarity Index)
def fsim(ref_img, dist_img):
"""
Computes FSIM (Feature Similarity Index) for grayscale images.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
# FSIM is based on gradient magnitude and phase congruency, here simplified
score = structural_similarity(ref_grad, dist_grad, data_range=1.0)
return score
# VIFc (Color Visual Information Fidelity)
def vifc(ref_img, dist_img):
"""
Computes VIF (Visual Information Fidelity) for color images by averaging the VIF
across the YUV color channels.
"""
ref_yuv = rgb2yuv(ref_img)
dist_yuv = rgb2yuv(dist_img)
# Compute VIF for each YUV channel
vif_y = vif(ref_yuv[:, :, 0], dist_yuv[:, :, 0])
vif_u = vif(ref_yuv[:, :, 1], dist_yuv[:, :, 1])
vif_v = vif(ref_yuv[:, :, 2], dist_yuv[:, :, 2])
vifc_value = (vif_y + vif_u + vif_v) / 3
return vifc_value
# VIF (used in VIFc)
def vif(ref_img, dist_img):
"""
Computes VIF (Visual Information Fidelity) based on entropy for grayscale images.
"""
epsilon = 1e-10
ref_img_clipped = np.clip(ref_img, epsilon, 1)
dist_img_clipped = np.clip(dist_img, epsilon, 1)
# Compute entropy
ref_entropy = -np.sum(ref_img_clipped * np.log2(ref_img_clipped))
dist_entropy = -np.sum(dist_img_clipped * np.log2(dist_img_clipped))
vif_value = ref_entropy / dist_entropy if dist_entropy != 0 else float('inf')
return vif_value
if __name__ == "__main__":
# Tested:
# C-SSIM (Color SSIM)
# FSIMc (Color Feature Similarity Index for Color Images)
# VIFc (Color Visual Information Fidelity for Color Images)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all color-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
@@ -0,0 +1,127 @@
"""
This module contains functions for computing frequency and spectral-based image quality metrics,
such as FIQ (Fourier-based Image Quality), SRSIM (Spectral Residual-based Similarity),
and several other metrics from the sewar library, including ERGAS, SCC, SAM, and D-lambda.
These metrics evaluate the similarity between images in the frequency or spectral domain.
Functions:
- compute_all: Computes all frequency and spectral-based image quality metrics.
- load_image: Loads an image and converts it to floating-point format.
- fiq: Computes the Fourier-based Image Quality (FIQ) metric.
- srsim: Computes the Spectral Residual-based Similarity (SRSIM).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from numpy.fft import fft2, fftshift
from sewar import ergas, scc, sam, d_lambda
def compute_all(ref_path, dist_path):
"""
Computes multiple frequency domain and spectral-based image quality metrics
between a reference and distorted image.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
output = {}
metrics = [
("FIQ", lambda: fiq(ref_img, dist_img)),
("SRSIM", lambda: srsim(ref_img, dist_img)),
("ERGAS", lambda: ergas(ref_img, dist_img)),
("SCC", lambda: scc(ref_img, dist_img)),
("SAM", lambda: sam(ref_img, dist_img)),
("D-lambda", lambda: d_lambda(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image from the given path and converts it to floating-point format.
"""
img = io.imread(path)
img = img_as_float(img)
return img
# FIQ (Fourier-based Image Quality Metric)
def fiq(ref_img, dist_img):
"""
Computes the Fourier-based Image Quality (FIQ) metric by comparing the magnitude spectra of
the reference and distorted images' Fourier transforms.
"""
# Compute the Fourier transforms of both images
ref_fft = fft2(ref_img)
dist_fft = fft2(dist_img)
# Shift zero frequency to the center
ref_fft_shift = fftshift(ref_fft)
dist_fft_shift = fftshift(dist_fft)
# Compute the magnitude spectrum
ref_magnitude = np.abs(ref_fft_shift)
dist_magnitude = np.abs(dist_fft_shift)
# Compute the similarity in the frequency domain
fiq_value = np.mean(np.abs(ref_magnitude - dist_magnitude))
return 1 / (1 + fiq_value) # Inverted for similarity
# SRSIM (Spectral Residual-based Similarity)
def srsim(ref_img, dist_img):
"""
Computes the Spectral Residual-based Similarity (SRSIM) metric by comparing the
spectral residuals of the reference and distorted images.
"""
# Compute the Fourier transform
ref_fft = fft2(ref_img)
dist_fft = fft2(dist_img)
# Compute the magnitude and log of the magnitude
ref_magnitude = np.abs(ref_fft)
dist_magnitude = np.abs(dist_fft)
ref_log_magnitude = np.log(ref_magnitude + 1e-10)
dist_log_magnitude = np.log(dist_magnitude + 1e-10)
# Compute the spectral residuals
ref_residual = ref_log_magnitude - np.mean(ref_log_magnitude)
dist_residual = dist_log_magnitude - np.mean(dist_log_magnitude)
# Compute the similarity between spectral residuals
srsim_value = np.mean(np.abs(ref_residual - dist_residual))
return 1 / (1 + srsim_value) # Inverted for similarity
if __name__ == "__main__":
# Tested:
# FIQ (Fourier-based Image Quality)
# SRSIM (Spectral Residual-based Similarity)
# ERGAS (Erreur Relative Globale Adimensionnelle de Synthèse)
# SCC (Spatial Correlation Coefficient)
# RASE (Relative Average Spectral Error)
# SAM (Spectral Angle Mapper)
# D-lambda (Spectral Distortion Index)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all frequency-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
@@ -0,0 +1,121 @@
"""
This module contains functions for computing gradient and edge-based image quality metrics:
GMSD (Gradient Magnitude Similarity Deviation), G-SSIM (Gradient-based Structural Similarity),
and ESIM (Edge Similarity Index).
These metrics evaluate the similarity between images based on their gradients
or edge information.
Functions:
- compute_all: Computes all gradient and edge-based image quality metrics.
- load_image: Loads an image and converts it to grayscale.
- gmsd: Computes the Gradient Magnitude Similarity Deviation (GMSD).
- g_ssim: Computes the Gradient-based Structural Similarity (G-SSIM).
- esim: Computes the Edge Similarity Index (ESIM).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from skimage.color import rgb2gray # pylint: disable=E0611
from skimage.metrics import structural_similarity # pylint: disable=E0611
from skimage.filters import sobel # pylint: disable=E0611
def compute_all(ref_path, dist_path):
"""
Computes gradient and edge-based image quality metrics between images.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
output = {}
metrics = [
("GMSD", lambda: gmsd(ref_img, dist_img)),
("G-SSIM", lambda: g_ssim(ref_img, dist_img)),
("ESIM", lambda: esim(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image, converts it to floating-point, and transforms it to grayscale if necessary.
"""
img = io.imread(path) # Load the image using skimage's imread
img = img_as_float(img) # Convert image to float values in range [0, 1]
# Convert to grayscale if image is in RGB format
if img.ndim == 3:
img = rgb2gray(img)
return img
# Gradient Magnitude Similarity Deviation (GMSD)
def gmsd(ref_img, dist_img):
"""
Computes the Gradient Magnitude Similarity Deviation (GMSD) by comparing
the gradient magnitudes of the reference and distorted images.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
# GMSD is the standard deviation of gradient magnitude differences
gmsd_value = np.sqrt(np.mean((ref_grad - dist_grad) ** 2))
return gmsd_value
# Gradient-based SSIM (G-SSIM)
def g_ssim(ref_img, dist_img):
"""
Computes the Gradient-based Structural Similarity (G-SSIM) by comparing
the gradients of the reference and distorted images using SSIM.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
# SSIM between gradients
score = structural_similarity(ref_grad, dist_grad, data_range=1.0)
return score
# Edge Similarity Index (ESIM)
def esim(ref_img, dist_img):
"""
Computes the Edge Similarity Index (ESIM) by comparing the edges of the
reference and distorted images using the Sobel filter.
"""
# Apply Sobel filter to extract edges
ref_edges = sobel(ref_img)
dist_edges = sobel(dist_img)
# Calculate the absolute difference between edge maps
esim_value = np.mean(np.abs(ref_edges - dist_edges))
return 1 - esim_value # ESIM is often 1 minus the edge difference for similarity
# TESTED
if __name__ == "__main__":
# Tested:
# GMSD (Gradient Magnitude Similarity Deviation)
# G-SSIM (Gradient-based Structural Similarity)
# ESIM (Edge Similarity Index)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all gradient and edge-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
@@ -0,0 +1,97 @@
"""
This module contains functions for computing information-theoretic image quality metrics,
such as VIF (Visual Information Fidelity) and VIFp (Visual Information Fidelity in Pixel Domain).
These metrics evaluate the similarity between reference and distorted images by analyzing
the amount of information preserved in the distorted image.
Functions:
- compute_all: Computes all information-theoretic image quality metrics.
- load_image: Loads an image and converts it to floating-point format.
- vif: Computes the Visual Information Fidelity (VIF).
- vifp: Computes the Visual Information Fidelity in the Pixel Domain (VIFp).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
def compute_all(ref_path, dist_path):
"""
Computes multiple information-theoretic image quality metrics.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
output = {}
metrics = [
("VIF", lambda: vif(ref_img, dist_img)),
("VIFp", lambda: vifp(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image from the given path and converts it to floating-point format.
"""
img = io.imread(path)
img = img_as_float(img)
return img
# VIF (Visual Information Fidelity)
def vif(ref_img, dist_img):
"""
Computes the Visual Information Fidelity (VIF) metric by comparing
the entropy of the reference and distorted images.
"""
# Compute the entropy of both images
ref_entropy = -np.sum(ref_img * np.log2(ref_img + 1e-10))
dist_entropy = -np.sum(dist_img * np.log2(dist_img + 1e-10))
# VIF score based on the ratio of information fidelity
vif_value = ref_entropy / dist_entropy if dist_entropy != 0 else float('inf')
return vif_value
# VIFp (Visual Information Fidelity in the Pixel Domain)
def vifp(ref_img, dist_img):
"""
Computes the Visual Information Fidelity in the Pixel Domain (VIFp) metric by analyzing
the mean squared error and pixel variance between the reference and distorted images.
"""
# Compute the mean squared error (MSE)
diff = ref_img - dist_img
mse_value = np.mean(diff ** 2)
# Visual information fidelity based on MSE and pixel variance
ref_variance = np.var(ref_img)
vifp_value = 1 - mse_value / ref_variance if ref_variance != 0 else float('inf')
return vifp_value
if __name__ == "__main__":
# Tested:
# VIF (Visual Information Fidelity)
# VIFp (Visual Information Fidelity in the Pixel Domain)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all information-theoretic metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
@@ -0,0 +1,143 @@
"""
This module contains functions for computing perceptual and HVS-based (Human Visual System)
IQ metrics: VSNR (Visual Signal-to-Noise Ratio), PIQE (Perceptual Image Quality Evaluator),
UQI (Universal Quality Index), and PSM (Perceptual Similarity Metric).
These metrics evaluate the similarity between reference and distorted images
by considering perceptual factors and human visual characteristics.
Functions:
- compute_all: Computes all perceptual and HVS-based image quality metrics.
- load_image: Loads an image and converts it to floating-point format.
- vsnr: Computes the Visual Signal-to-Noise Ratio (VSNR).
- piqe: Computes the Perceptual Image Quality Evaluator (PIQE).
- uqi: Computes the Universal Quality Index (UQI).
- psm: Computes the Perceptual Similarity Metric (PSM).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from skimage.filters import sobel # pylint: disable=E0611
def compute_all(ref_path, dist_path):
"""
Computes multiple perceptual and HVS-based image quality metrics.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
output = {}
metrics = [
("VSNR", lambda: vsnr(ref_img, dist_img)),
("PIQE", lambda: piqe(ref_img, dist_img)),
("UQI", lambda: uqi(ref_img, dist_img)),
("PSM", lambda: psm(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image from the given path and converts it to floating-point format.
"""
img = io.imread(path)
img = img_as_float(img)
return img
# VSNR (Visual Signal-to-Noise Ratio)
def vsnr(ref_img, dist_img):
"""
Computes the Visual Signal-to-Noise Ratio (VSNR) by comparing the signal power
and noise power between the reference and distorted images.
"""
signal_power = np.mean(ref_img ** 2)
noise_power = np.mean((ref_img - dist_img) ** 2)
# Perceptual component: Use a simple threshold
perceptual_threshold = 0.01
vsnr_value = 10 * np.log10(signal_power / (noise_power + perceptual_threshold))
return vsnr_value
# PIQE (Perceptual Image Quality Evaluator)
def piqe(ref_img, dist_img):
"""
Computes the Perceptual Image Quality Evaluator (PIQE) by calculating
the mean absolute difference as a proxy for perceptual distortion.
"""
# PIQE typically measures distortions directly in images, but here we'll simulate it
# by using the Mean Absolute Difference (MAD) as a perceptual proxy
mad_value = np.mean(np.abs(ref_img - dist_img))
# PIQE value is inversely proportional to the perceptual distortion
piqe_value = 100 / (1 + mad_value)
return piqe_value
# UQI (Universal Quality Index)
def uqi(ref_img, dist_img):
"""
Computes the Universal Quality Index (UQI) by comparing
statistical features between the reference and distorted images.
"""
mean_ref = np.mean(ref_img)
mean_dist = np.mean(dist_img)
var_ref = np.var(ref_img)
var_dist = np.var(dist_img)
covariance = np.mean((ref_img - mean_ref) * (dist_img - mean_dist))
# UQI formula
numerator = 4 * covariance * mean_ref * mean_dist
denominator = (var_ref + var_dist) * (mean_ref ** 2 + mean_dist ** 2)
uqi_value = numerator / denominator
return uqi_value
# PSM (Perceptual Similarity Metric)
def psm(ref_img, dist_img):
"""
Computes the Perceptual Similarity Metric (PSM) by comparing the edge similarity
between the reference and distorted images.
"""
# Edge similarity based perceptual metric
ref_edges = sobel(ref_img)
dist_edges = sobel(dist_img)
# Compute similarity between edge maps
edge_similarity = np.mean(1 - np.abs(ref_edges - dist_edges))
# PSM value based on edge similarity
psm_value = edge_similarity * 100 # Scale to 0-100
return psm_value
if __name__ == "__main__":
# Tested:
# VSNR (Visual Signal-to-Noise Ratio)
# PIQE (Perceptual Image Quality Evaluator)
# UQI (Universal Quality Index)
# PSM (Perceptual Similarity Metric)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all perceptual-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
+120
View File
@@ -0,0 +1,120 @@
"""
This module contains functions for computing pixel-based image quality metrics,
such as MSE (Mean Squared Error), RMSE (Root Mean Squared Error), PSNR (Peak Signal-to-Noise Ratio),
PSNR-B (Block Sensitive PSNR), SNR (Signal-to-Noise Ratio), and MAE (Mean Absolute Error).
These metrics evaluate the similarity between reference and distorted images
by directly comparing pixel values.
Functions:
- compute_all: Computes all pixel-based image quality metrics.
- load_image: Loads an image and converts it to floating-point format.
- mse: Computes the Mean Squared Error (MSE).
- psnr: Computes the Peak Signal-to-Noise Ratio (PSNR).
- snr: Computes the Signal-to-Noise Ratio (SNR).
- mae: Computes the Mean Absolute Error (MAE).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from sewar import rmse, psnrb
def compute_all(ref_path, dist_path):
"""
Computes multiple pixel-based image quality metrics.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
output = {}
metrics = [
("MSE", lambda: mse(ref_img, dist_img)),
("RMSE", lambda: rmse(ref_img, dist_img)),
("PSNR", lambda: psnr(ref_img, dist_img)),
("PSNR-B", lambda: psnrb(ref_img, dist_img)),
("SNR", lambda: snr(ref_img, dist_img)),
("MAE", lambda: mae(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image from the given path and converts it to floating-point format.
"""
img = io.imread(path)
img = img_as_float(img)
return img
# Mean Squared Error (MSE)
def mse(ref_img, dist_img):
"""
Computes the Mean Squared Error (MSE) between the reference and distorted images.
"""
return np.mean((ref_img - dist_img) ** 2)
# Peak Signal-to-Noise Ratio (PSNR)
def psnr(ref_img, dist_img):
"""
Computes the Peak Signal-to-Noise Ratio (PSNR) by comparing the mean squared error
between the reference and distorted images.
"""
mse_value = mse(ref_img, dist_img)
if mse_value == 0:
return float('inf') # Perfect match, no error
max_pixel_value = 1.0 # Assuming the images are normalized to [0, 1]
return 20 * np.log10(max_pixel_value / np.sqrt(mse_value))
# Signal-to-Noise Ratio (SNR)
def snr(ref_img, dist_img):
"""
Computes the Signal-to-Noise Ratio (SNR) by comparing the signal power
and noise power between the reference and distorted images.
"""
signal_power = np.mean(ref_img ** 2)
noise_power = np.mean((ref_img - dist_img) ** 2)
if noise_power == 0:
return float('inf') # Perfect match, no noise
return 10 * np.log10(signal_power / noise_power)
# Mean Absolute Error (MAE)
def mae(ref_img, dist_img):
"""
Computes the Mean Absolute Error (MAE) between the reference and distorted images.
"""
return np.mean(np.abs(ref_img - dist_img))
if __name__ == "__main__":
# Tested:
# MSE (Mean Squared Error)
# RMSE (Root Mean Squared Error)
# PSNR (Peak Signal-to-Noise Ratio)
# PSNR-B (Block Sensitive - Peak Signal-to-Noise Ratio)
# SNR (Signal-to-Noise Ratio)
# MAE (Mean Absolute Error)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all pixel-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
+158
View File
@@ -0,0 +1,158 @@
"""
This module contains functions for computing Peak Signal-to-Noise Ratio (PSNR)-based
image quality metrics, such as standard PSNR, weighted PSNR, PSNR-HVS, PSNR-HVS-M,
and logarithmic PSNR.
These metrics evaluate the similarity between a reference and a distorted image
by analyzing pixel intensity differences.
Functions:
- compute_all: Computes multiple PSNR-based image quality metrics.
- load_image: Loads an image and converts it to the specified color scheme.
- psnr: Computes the standard Peak Signal-to-Noise Ratio (PSNR).
- w_psnr: Computes the Weighted PSNR (W-PSNR).
- psnr_hvs: Computes PSNR based on Human Visual System (HVS) properties.
- psnr_hvs_m: Computes PSNR with HVS modifications (PSNR-HVS-M).
- log_psnr: Computes logarithmic PSNR (Log-PSNR).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from skimage.metrics import peak_signal_noise_ratio # pylint: disable=E0611
from skimage.color import rgb2gray, rgb2yuv # pylint: disable=E0611
def compute_all(ref_path, dist_path):
"""
Computes multiple PSNR-based image quality metrics.
"""
ref_img_rgb = load_image(ref_path, 'rgb')
dist_img_rgb = load_image(dist_path, 'rgb')
ref_img_yuv = load_image(ref_path, 'yuv')
dist_img_yuv = load_image(dist_path, 'yuv')
output = {}
metrics = [
("cPSNR", lambda: cpsnr(ref_img_rgb, dist_img_rgb)),
("W-PSNR", lambda: w_psnr(ref_img_rgb, dist_img_rgb)),
("PSNR-HVS", lambda: psnr_hvs(ref_img_yuv, dist_img_yuv)),
("PSNR-HVS-M", lambda: psnr_hvs_m(ref_img_yuv, dist_img_yuv)),
("Log-PSNR", lambda: log_psnr(ref_img_rgb, dist_img_rgb)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
def load_image(path, scheme):
"""
Loads an image and converts it to the specified color scheme.
Parameters:
path (str): Path to the image file.
scheme (str): The color scheme to convert to ('rgb', 'gray', 'yuv').
Returns:
np.ndarray: The loaded image in the specified format.
"""
img = io.imread(path)
img = img_as_float(img)
if scheme == 'gray':
img = rgb2gray(img)
elif scheme == 'yuv':
img = rgb2yuv(img)
return img
def cpsnr(ref_img, dist_img):
"""
Computes the standard Peak Signal-to-Noise Ratio (PSNR).
"""
psnr_r = peak_signal_noise_ratio(ref_img[:, :, 0], dist_img[:, :, 0])
psnr_g = peak_signal_noise_ratio(ref_img[:, :, 1], dist_img[:, :, 1])
psnr_b = peak_signal_noise_ratio(ref_img[:, :, 2], dist_img[:, :, 2])
return (psnr_r + psnr_g + psnr_b) / 3
def w_psnr(ref_img, dist_img):
"""
Computes the Weighted PSNR (W-PSNR).
"""
height, width, _ = ref_img.shape
weight_matrix = np.ones((height, width))
weight_matrix[height // 4:3 * height // 4, width // 4:3 * width // 4] = 2.0
mse_r = np.mean(weight_matrix * (ref_img[:, :, 0] - dist_img[:, :, 0]) ** 2)
mse_g = np.mean(weight_matrix * (ref_img[:, :, 1] - dist_img[:, :, 1]) ** 2)
mse_b = np.mean(weight_matrix * (ref_img[:, :, 2] - dist_img[:, :, 2]) ** 2)
if mse_r == 0 or mse_g == 0 or mse_b == 0:
return np.inf
psnr_weighted_r = 10 * np.log10(1 / mse_r)
psnr_weighted_g = 10 * np.log10(1 / mse_g)
psnr_weighted_b = 10 * np.log10(1 / mse_b)
return (psnr_weighted_r + psnr_weighted_g + psnr_weighted_b) / 3
def psnr_hvs(ref_img, dist_img):
"""
Computes PSNR based on Human Visual System (HVS) properties.
"""
contrast_weight = np.ones(ref_img[:, :, 0].shape) * 0.9
contrast_weight[ref_img[:, :, 0] > 0.5] = 0.8
mse = np.mean(contrast_weight * (ref_img[:, :, 0] - dist_img[:, :, 0]) ** 2)
if mse == 0:
return np.inf
return 10 * np.log10(1 / mse)
def psnr_hvs_m(ref_img, dist_img):
"""
Computes PSNR with Human Visual System modifications (PSNR-HVS-M).
"""
mask_weight = np.ones(ref_img.shape) * 0.7
mask_weight[ref_img > 0.7] = 0.6
mse = np.mean(mask_weight * (ref_img - dist_img) ** 2)
if mse == 0:
return np.inf
return 10 * np.log10(1 / mse)
def log_psnr(ref_img, dist_img):
"""
Computes logarithmic PSNR (Log-PSNR).
"""
psnr_score = cpsnr(ref_img, dist_img)
return np.log1p(psnr_score)
if __name__ == "__main__":
# Tested:
# cPSNR (color Peak Signal-to-Noise Ratio)
# W-PSNR (Weighted Peak Signal-to-Noise Ratio)
# PSNR-HVS (Human Visual System-based PSNR)
# PSNR-HVS-M (Modified Human Visual System PSNR)
# Log-PSNR (Logarithmic cPSNR)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all pixel-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
+113
View File
@@ -0,0 +1,113 @@
"""
This module contains functions for computing region-based image quality metrics,
such as R-SSIM (Region-based SSIM) and L-SSIM (Local SSIM).
It uses structural similarity indices to evaluate the similarity between
reference and distorted images.
Functions:
- compute_all: Computes all region-based image quality metrics.
- load_image: Loads an image and converts it to grayscale.
- r_ssim: Computes the Region-based SSIM for a specific region of the image.
- l_ssim: Computes the Local SSIM by sliding a window across the image.
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float
from skimage.metrics import structural_similarity # pylint: disable=E0611
from skimage.color import rgb2gray # pylint: disable=E0611
def compute_all(ref_path, dist_path):
"""
Computes multiple region-based image quality metrics.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
output = {}
metrics = [
("R-SSIM", lambda: r_ssim(ref_img, dist_img)),
("L-SSIM", lambda: l_ssim(ref_img, dist_img)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image, converts it to floating-point, and transforms it to grayscale if necessary.
"""
img = io.imread(path) # Load the image using skimage's imread
img = img_as_float(img) # Convert image to float values in range [0, 1]
# Convert to grayscale if image is in RGB format
if img.ndim == 3:
img = rgb2gray(img)
return img
# R-SSIM (Region-based SSIM)
def r_ssim(ref_img, dist_img):
"""
Computes the SSIM (Structural Similarity Index) over the central region of the image.
"""
height, width = ref_img.shape
# Define a central region of the image (taking the central half in both directions)
center_ref = ref_img[height // 4: 3 * height // 4, width // 4: 3 * width // 4]
center_dist = dist_img[height // 4: 3 * height // 4, width // 4: 3 * width // 4]
# Compute SSIM for the central region only
score = structural_similarity(center_ref, center_dist, data_range=1.0)
return score
# L-SSIM (Local SSIM)
def l_ssim(ref_img, dist_img, window_size=8):
"""
Computes the SSIM (Structural Similarity Index) locally by sliding a window over the images.
"""
height, width = ref_img.shape
# List to hold SSIM values for each window
local_ssim_values = []
# Slide the window across the image
for i in range(0, height - window_size + 1, window_size):
for j in range(0, width - window_size + 1, window_size):
# Extract local windows from the reference and distorted images
ref_win = ref_img[i:i + window_size, j:j + window_size]
dist_win = dist_img[i:i + window_size, j:j + window_size]
# Compute SSIM for the local region (window)
local_ssim = structural_similarity(ref_win, dist_win, data_range=1.0)
local_ssim_values.append(local_ssim)
# Return the mean SSIM value across all windows
return np.mean(local_ssim_values)
if __name__ == "__main__":
# Tested:
# R-SSIM (Region-based SSIM)
# L-SSIM (Local SSIM)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all region-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
+250
View File
@@ -0,0 +1,250 @@
"""
This module contains functions for computing SSIM-based and gradient-based image quality metrics,
such as SSIM (Structural Similarity Index), MS-SSIM (Multi-Scale SSIM), G-SSIM (Gradient SSIM),
IW-SSIM (Information Weighted SSIM), FSIM (Feature Similarity Index), DSSIM (Difference SSIM),
and GMS+CMS (Gradient Magnitude and Color Similarity).
These metrics evaluate the similarity between reference and distorted images
by considering structural, gradient, and feature-based aspects.
Functions:
- compute_all: Computes all SSIM-based and gradient-based image quality metrics.
- load_image: Loads an image and converts it to a specified format.
- ssim: Computes the Structural Similarity Index (SSIM).
- ms_ssim: Computes the Multi-Scale SSIM (MS-SSIM).
- cw_ssim: Computes the Complex Wavelet SSIM (CW-SSIM).
- g_ssim: Computes the Gradient Structural Similarity Index (G-SSIM).
- w_ssim: Computes the Weighted SSIM (W-SSIM).
- iw_ssim: Computes the Information Weighted SSIM (IW-SSIM).
- fsim: Computes the Feature Similarity Index (FSIM).
- r_ssim: Computes the Region-Based SSIM (R-SSIM).
- dssim: Computes the Difference SSIM (DSSIM).
- gmsd: Computes the Gradient Magnitude Similarity Deviation (GMSD).
- c_ssim: Computes the Color SSIM (C-SSIM).
"""
from time import time as now
import numpy as np
import pywt
from skimage import io, img_as_float, img_as_ubyte
from skimage.metrics import structural_similarity # pylint: disable=E0611
from skimage.color import rgb2gray, rgb2yuv # pylint: disable=E0611
from skimage.filters import sobel # pylint: disable=E0611
from sewar import msssim as multiscale_ssim
def compute_all(ref_path, dist_path):
"""
Computes multiple SSIM-based and FSIM-based image quality metrics.
"""
ref_img_rgb = load_image(ref_path, 'rgb')
dist_img_rgb = load_image(dist_path, 'rgb')
ref_img_gray = load_image(ref_path, 'gray')
dist_img_gray = load_image(dist_path, 'gray')
ref_img_yuv = load_image(ref_path, 'yuv')
dist_img_yuv = load_image(dist_path, 'yuv')
output = {}
metrics = [
("SSIM", lambda: ssim(ref_img_rgb, dist_img_rgb)),
("MS-SSIM", lambda: ms_ssim(ref_img_rgb, dist_img_rgb)),
("CW-SSIM", lambda: cw_ssim(ref_img_gray, dist_img_gray)),
("G-SSIM", lambda: g_ssim(ref_img_rgb, dist_img_rgb)),
("W-SSIM", lambda: w_ssim(ref_img_rgb, dist_img_rgb)),
("IW-SSIM", lambda: iw_ssim(ref_img_rgb, dist_img_rgb)),
("FSIM", lambda: fsim(ref_img_gray, dist_img_gray)),
("R-SSIM", lambda: r_ssim(ref_img_gray, dist_img_gray)),
("DSSIM", lambda: dssim(ref_img_rgb, dist_img_rgb)),
("GMSD", lambda: gmsd(ref_img_gray, dist_img_gray)),
("C-SSIM", lambda: c_ssim(ref_img_yuv, dist_img_yuv)),
]
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path, scheme):
"""
Loads an image and converts it to the specified color scheme.
"""
img = io.imread(path)
img = img_as_float(img)
if scheme == 'gray':
img = rgb2gray(img)
elif scheme == 'yuv':
img = rgb2yuv(img)
return img
# Standard SSIM
def ssim(ref_img, dist_img):
"""
Computes the Structural Similarity Index (SSIM).
"""
if ref_img.ndim == 3 and dist_img.ndim == 3:
# Color images: Compute SSIM for each channel and average the results
ssim_r = structural_similarity(ref_img[:, :, 0], dist_img[:, :, 0], data_range=1.0)
ssim_g = structural_similarity(ref_img[:, :, 1], dist_img[:, :, 1], data_range=1.0)
ssim_b = structural_similarity(ref_img[:, :, 2], dist_img[:, :, 2], data_range=1.0)
return (ssim_r + ssim_g + ssim_b) / 3
elif ref_img.ndim == 2 and dist_img.ndim == 2:
# Grayscale images: Compute SSIM directly
return structural_similarity(ref_img, dist_img, data_range=1.0)
# Multi-Scale SSIM (MS-SSIM)
def ms_ssim(ref_img, dist_img):
"""
Computes the Multi-Scale Structural Similarity Index (MS-SSIM).
"""
ref_img = img_as_ubyte(ref_img)
dist_img = img_as_ubyte(dist_img)
return multiscale_ssim(ref_img, dist_img)
# Complex Wavelet SSIM (CW-SSIM)
def cw_ssim(ref_img, dist_img):
"""
Computes the Complex Wavelet Structural Similarity Index (CW-SSIM).
"""
ref_coeffs = pywt.dwtn(ref_img, 'haar')
dist_coeffs = pywt.dwtn(dist_img, 'haar')
# Compute the SSIM on the real and imaginary parts of the complex wavelet
score = np.mean([
structural_similarity(ref_coeffs[k].real, dist_coeffs[k].real, data_range=1.0) +
structural_similarity(ref_coeffs[k].imag, dist_coeffs[k].imag, data_range=1.0)
for k in ref_coeffs.keys()
]) / 2.0
return score
# Gradient-based SSIM (G-SSIM)
def g_ssim(ref_img, dist_img):
"""
Computes Gradient-based SSIM (G-SSIM).
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
return ssim(ref_grad, dist_grad)
# Weighted SSIM (W-SSIM) - Using a simple weighted region-based SSIM
def w_ssim(ref_img, dist_img, weight=0.7):
"""
Computes Weighted SSIM (W-SSIM) with a focus on center regions.
"""
height, width, _ = ref_img.shape
center_region = ref_img[height // 4: 3 * height // 4, width // 4: 3 * width // 4, :]
center_dist = dist_img[height // 4: 3 * height // 4, width // 4: 3 * width // 4, :]
outer_region = np.copy(ref_img)
outer_region[height // 4: 3 * height // 4, width // 4: 3 * width // 4, :] = 0
center_ssim = ssim(center_region, center_dist)
outer_ssim = ssim(outer_region, dist_img)
weighted_score = weight * center_ssim + (1 - weight) * outer_ssim
return weighted_score
# Information Content Weighted SSIM (IW-SSIM)
def iw_ssim(ref_img, dist_img):
"""
Computes Information Content Weighted SSIM (IW-SSIM).
"""
entropy_ref = -ref_img * np.log2(ref_img + 1e-10)
entropy_dist = -dist_img * np.log2(dist_img + 1e-10)
local_ssim = ssim(ref_img, dist_img)
score = np.mean(entropy_ref * local_ssim + entropy_dist * local_ssim)
return score
# Feature SIMilarity Index (FSIM)
def fsim(ref_img, dist_img):
"""
Computes the Feature SIMilarity Index (FSIM).
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
score = structural_similarity(ref_grad, dist_grad, data_range=1.0)
return score
# Region-Based SSIM (R-SSIM)
def r_ssim(ref_img, dist_img):
"""
Computes the Region-Based SSIM (R-SSIM).
"""
height, width = ref_img.shape
center_ref = ref_img[height // 4: 3 * height // 4, width // 4: 3 * width // 4]
center_dist = dist_img[height // 4: 3 * height // 4, width // 4: 3 * width // 4]
score = structural_similarity(center_ref, center_dist, data_range=1.0)
return score
# Difference SSIM (DSSIM)
def dssim(ref_img, dist_img):
"""
Computes the Difference Structural Similarity Index (DSSIM).
"""
score = ssim(ref_img, dist_img)
return (1 - score) / 2
# Color SSIM (C-SSIM)
def c_ssim(ref_img, dist_img):
"""
Computes Color SSIM (C-SSIM) on the YUV color space.
"""
y_ssim = structural_similarity(ref_img[:, :, 0], dist_img[:, :, 0], data_range=1.0)
u_ssim = structural_similarity(ref_img[:, :, 1], dist_img[:, :, 1], data_range=1.0)
v_ssim = structural_similarity(ref_img[:, :, 2], dist_img[:, :, 2], data_range=1.0)
return (y_ssim + u_ssim + v_ssim) / 3
# Gradient Magnitude Similarity Deviation (GMSD)
def gmsd(ref_img, dist_img):
"""
Computes Gradient Magnitude Similarity Deviation (GMSD)
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
return np.sqrt(np.mean((ref_grad - dist_grad) ** 2))
if __name__ == "__main__":
# Tested:
# SSIM (Structural Similarity Index)
# MS-SSIM (Multi-Scale SSIM)
# CW-SSIM (Complex Wavelet SSIM)
# G-SSIM (Gradient-based SSIM)
# W-SSIM (Weighted SSIM)
# IW-SSIM (Information Content Weighted SSIM)
# FSIM (Feature SIMilarity Index)
# R-SSIM (Region-based SSIM)
# DSSIM (Difference SSIM)
# C-SSIM (Color SSIM)
# GMSD (Gradient Magnitude Similarity Deviation)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all region-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
@@ -0,0 +1,215 @@
"""
This module contains functions for computing SSIM-based and gradient-based image quality metrics,
such as SSIM (Structural Similarity Index), MS-SSIM (Multi-Scale SSIM), G-SSIM (Gradient SSIM),
IW-SSIM (Information Weighted SSIM), FSIM (Feature Similarity Index), MS-FSIM (Multi-Scale FSIM),
DSSIM (Difference SSIM), and GMS+CMS (Gradient Magnitude and Color Similarity).
These metrics evaluate the similarity between reference and distorted images
by considering structural, gradient, and feature-based aspects.
Functions:
- compute_all: Computes all SSIM-based and gradient-based image quality metrics.
- load_image: Loads an image and converts it to floating-point format.
- ssim: Computes the Structural Similarity Index (SSIM).
- ms_ssim: Computes the Multi-Scale SSIM (MS-SSIM).
- g_ssim: Computes the Gradient Structural Similarity Index (G-SSIM).
- iw_ssim: Computes the Information Weighted SSIM (IW-SSIM).
- fsim: Computes the Feature Similarity Index (FSIM).
- ms_fsim: Computes the Multi-Scale Feature Similarity Index (MS-FSIM).
- dssim: Computes the Difference SSIM (DSSIM).
- gms_cms: Computes the combined Gradient Magnitude and Color Similarity (GMS+CMS).
"""
from time import time as now
import numpy as np
from skimage import io, img_as_float, img_as_ubyte
from skimage.metrics import structural_similarity # pylint: disable=E0611
from skimage.color import rgb2gray, rgb2yuv # pylint: disable=E0611
from skimage.filters import sobel # pylint: disable=E0611
from sewar import msssim as multiscale_ssim
def compute_all(ref_path, dist_path):
"""
Computes multiple SSIM-based and gradient-based image quality metrics between
a reference and distorted image.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
ref_img_rgb = load_image(ref_path, 'rgb')
dist_img_rgb = load_image(dist_path, 'rgb')
metrics = [
("SSIM", lambda: ssim(ref_img, dist_img)),
("MS-SSIM", lambda: ms_ssim(ref_img, dist_img)),
("G-SSIM", lambda: g_ssim(ref_img, dist_img)),
("IW-SSIM", lambda: iw_ssim(ref_img, dist_img)),
("FSIM", lambda: fsim(ref_img, dist_img)),
("MS-FSIM", lambda: ms_fsim(ref_img, dist_img)),
("DSSIM", lambda: dssim(ref_img, dist_img)),
("GMS+CMS", lambda: gms_cms(ref_img_rgb, dist_img_rgb)),
]
output = {}
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path, scheme='gray'):
"""
Loads an image from the given path and converts it to floating-point format.
If the image is in RGB format, it is converted to grayscale.
"""
img = io.imread(path)
img = img_as_float(img)
if scheme == 'gray':
img = rgb2gray(img)
return img
# SSIM (Structural Similarity Index)
def ssim(ref_img, dist_img):
"""
Computes the Structural Similarity Index (SSIM) between the reference and distorted images.
"""
score = structural_similarity(ref_img, dist_img, data_range=1.0)
return score
# MS-SSIM (Multi-Scale SSIM)
def ms_ssim(ref_img, dist_img):
"""
Computes the Multi-Scale Structural Similarity Index (MS-SSIM) between images.
"""
ref_img = img_as_ubyte(ref_img)
dist_img = img_as_ubyte(dist_img)
score = abs(multiscale_ssim(ref_img, dist_img))
return score
# G-SSIM (Gradient Structural Similarity Index)
def g_ssim(ref_img, dist_img):
"""
Computes the Gradient Structural Similarity Index (G-SSIM) by comparing
the gradients of the reference and distorted images.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
score = structural_similarity(ref_grad, dist_grad, data_range=1.0)
return score
# IW-SSIM (Information Weighted SSIM)
def iw_ssim(ref_img, dist_img):
"""
Computes the Information Weighted Structural Similarity Index (IW-SSIM)
by weighting the SSIM value with local entropy information.
"""
entropy_ref = -ref_img * np.log2(ref_img + 1e-10)
entropy_dist = -dist_img * np.log2(dist_img + 1e-10)
local_ssim = structural_similarity(ref_img, dist_img, data_range=1.0)
score = np.mean(entropy_ref * local_ssim + entropy_dist * local_ssim)
return score
# FSIM (Feature Similarity Index)
def fsim(ref_img, dist_img):
"""
Computes the Feature Similarity Index (FSIM) by comparing the gradients of the reference
and distorted images.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
score = structural_similarity(ref_grad, dist_grad, data_range=1.0)
return score
# MS-FSIM (Multi-Scale Feature Similarity Index)
def ms_fsim(ref_img, dist_img):
"""
Computes the Multi-Scale Feature Similarity Index (MS-FSIM) by combining structural
and gradient similarity across multiple scales.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
# Multi-scale SSIM for structural similarity
structural_similarity_value = structural_similarity(ref_img, dist_img, data_range=1.0)
# FSIM based on gradient magnitude similarity
gradient_similarity = np.mean(1 - np.abs(ref_grad - dist_grad))
# Combine structural similarity and feature similarity (FSIM)
score = 0.5 * structural_similarity_value + 0.5 * gradient_similarity
return score
# DSSIM (Difference SSIM)
def dssim(ref_img, dist_img):
"""
Computes the Difference SSIM (DSSIM) as the dissimilarity measure derived from SSIM.
"""
score = structural_similarity(ref_img, dist_img, data_range=1.0)
score = (1 - score) / 2
return score
# GMS + CMS (Gradient Magnitude and Color Similarity)
def gms_cms(ref_img, dist_img):
"""
Computes the combined Gradient Magnitude Similarity (GMS) and Color Similarity (CMS)
between the reference and distorted images.
"""
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
# Gradient Magnitude Similarity (GMS)
gms_value = np.mean(1 - np.abs(ref_grad - dist_grad))
# Color Similarity (CMS)
ref_yuv = rgb2yuv(ref_img)
dist_yuv = rgb2yuv(dist_img)
y_similarity = structural_similarity(ref_yuv[:, :, 0], dist_yuv[:, :, 0], data_range=1.0)
u_similarity = structural_similarity(ref_yuv[:, :, 1], dist_yuv[:, :, 1], data_range=1.0)
v_similarity = structural_similarity(ref_yuv[:, :, 2], dist_yuv[:, :, 2], data_range=1.0)
cms_value = (y_similarity + u_similarity + v_similarity) / 3
# Combine GMS and CMS
score = 0.5 * gms_value + 0.5 * cms_value
return score
if __name__ == "__main__":
# Tested:
# SSIM (Structural Similarity Index)
# MS-SSIM (Multi-Scale SSIM)
# G-SSIM (Gradient SSIM)
# IW-SSIM (Information Weighted SSIM)
# FSIM (Feature Similarity Index)
# MS-FSIM (Multi-Scale FSIM)
# DSSIM (Difference SSIM)
# GMS + CMS (Gradient Magnitude and Color Similarity)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all structural-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")
+156
View File
@@ -0,0 +1,156 @@
"""
This module contains functions for computing wavelet-based image quality metrics,
such as W-SSIM (Wavelet-based Weighted SSIM), CW-SSIM (Complex Wavelet SSIM),
and SPIQ (Steerable Pyramid-based Image Quality Index).
These metrics evaluate the similarity between reference and distorted images
using wavelet and pyramid-based decompositions.
Functions:
- compute_all: Computes all wavelet-based image quality metrics.
- load_image: Loads an image and converts it to floating-point format.
- w_ssim: Computes the Wavelet-based Weighted SSIM (W-SSIM).
- cw_ssim: Computes the Complex Wavelet SSIM (CW-SSIM).
- spiq: Computes the Steerable Pyramid-based Image Quality Index (SPIQ).
"""
from time import time as now
import numpy as np
import pywt
from skimage import io, img_as_float
from skimage.color import rgb2gray # pylint: disable=E0611
from skimage.metrics import structural_similarity # pylint: disable=E0611
from skimage.filters import sobel # pylint: disable=E0611
# Function to compute all wavelet-based metrics
def compute_all(ref_path, dist_path):
"""
Computes multiple wavelet-based image quality metrics between
a reference and distorted image.
"""
ref_img = load_image(ref_path)
dist_img = load_image(dist_path)
metrics = [
("W-SSIM", lambda: w_ssim(ref_img, dist_img)),
("CW-SSIM", lambda: cw_ssim(ref_img, dist_img)),
("SPIQ", lambda: spiq(ref_img, dist_img)),
]
output = {}
for name, func in metrics:
start_time = now()
output[name] = (func(), now() - start_time)
return output
# Helper function to load images
def load_image(path):
"""
Loads an image, converts it to floating-point, and transforms it to grayscale if necessary.
"""
img = io.imread(path) # Load the image using skimage's imread
img = img_as_float(img) # Convert image to float values in range [0, 1]
# Convert to grayscale if image is in RGB format
if img.ndim == 3:
img = rgb2gray(img)
return img
# W-SSIM (Wavelet-based Weighted SSIM)
def w_ssim(ref_img, dist_img):
"""
Computes the Wavelet-based Weighted SSIM (W-SSIM) by applying a wavelet decomposition
and computing SSIM on the wavelet subbands.
"""
# Apply 2D discrete wavelet transform using 'haar'
ref_coeffs = pywt.dwtn(ref_img, 'haar')
dist_coeffs = pywt.dwtn(dist_img, 'haar')
# Compute SSIM for each level of the wavelet decomposition
ssim_values = []
for key in ref_coeffs.keys():
ref_band = ref_coeffs[key]
dist_band = dist_coeffs[key]
# Skip subbands that are too small for SSIM computation
if ref_band.shape[0] < 7 or ref_band.shape[1] < 7:
continue
min_dim = min(ref_band.shape)
win_size = min(7, min_dim) # Set window size to a smaller value if subband is small
if win_size % 2 == 0:
win_size -= 1 # Ensure win_size is odd
min_dim = min(ref_band.shape)
win_size = min(7, min_dim) # Set window size
if win_size % 2 == 0:
win_size -= 1 # Ensure win_size is odd
try:
# Compute SSIM for the subband with the specified win_size
ssimband = structural_similarity(ref_band, dist_band, win_size=win_size, data_range=1.0)
ssim_values.append(ssimband)
except ZeroDivisionError:
# In case of a division by zero error, skip this subband
continue
return np.mean(ssim_values) if ssim_values else 0
# CW-SSIM (Complex Wavelet SSIM)
def cw_ssim(ref_img, dist_img):
"""
Computes the Complex Wavelet SSIM (CW-SSIM) by performing a wavelet decomposition
and computing SSIM on the real and imaginary parts of the subbands.
"""
ref_coeffs = pywt.dwtn(ref_img, 'haar')
dist_coeffs = pywt.dwtn(dist_img, 'haar')
# Compute the SSIM on the real and imaginary parts of the complex wavelet
score = np.mean([
structural_similarity(ref_coeffs[k].real, dist_coeffs[k].real, data_range=1.0) +
structural_similarity(ref_coeffs[k].imag, dist_coeffs[k].imag, data_range=1.0)
for k in ref_coeffs.keys()
]) / 2.0
return score
# SPIQ (Steerable Pyramid-based Image Quality Index)
def spiq(ref_img, dist_img):
"""
Computes the Steerable Pyramid-based Image Quality Index (SPIQ)
by approximating the steerable pyramid decomposition with image gradients.
"""
# Apply steerable pyramid decomposition (simplified with gradients)
ref_grad = sobel(ref_img)
dist_grad = sobel(dist_img)
# Compute SSIM between gradient maps
score = structural_similarity(ref_grad, dist_grad, data_range=1.0)
return score
if __name__ == "__main__":
# Tested:
# W-SSIM (Wavelet-based Weighted SSIM)
# CW-SSIM (Complex Wavelet SSIM)
# SPIQ (Steerable Pyramid-based Image Quality Index)
# Paths to reference and distorted images
REF_IMG_PATH = "test_reference/001.jpg"
DIST_IMG_PATH = "test_distorted/001_CodeFace_1.4.jpg"
# Compute all wavelet-based metrics
results = compute_all(REF_IMG_PATH, DIST_IMG_PATH)
# Print results for each metric along with the time taken
for metric, (value, duration) in results.items():
print(f"{metric}: {value:.8g} (computed in {duration:.6f} seconds)")