Quantitatively check the quality of a compressed image by calculating the Peak Signal-to-Noise Ratio (PSNR) between two images. More info at https://code.adonline.id.au/peak-signal-to-noise-ratio-python/
#!/usr/bin/env python | |
from math import log10, sqrt | |
import cv2 | |
import numpy as np | |
import argparse | |
# Based on https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ | |
def options(): | |
parser = argparse.ArgumentParser(description="Read image metadata") | |
parser.add_argument("-o", "--original", help="Input image file.", required=True) | |
parser.add_argument("-c", "--copy", help="Input image file.", required=True) | |
args = parser.parse_args() | |
return args | |
def PSNR(original, compressed): | |
mse = np.mean((original - compressed) ** 2) | |
if(mse == 0): | |
return 100 | |
max_pixel = 255.0 | |
psnr = 20 * log10(max_pixel / sqrt(mse)) | |
return psnr | |
def main(): | |
# Get options | |
args = options() | |
# Import images | |
original = cv2.imread(args.original) | |
compressed = cv2.imread(args.copy, 1) | |
# Check for same size and ratio and report accordingly | |
ho, wo, _ = original.shape | |
hc, wc, _ = compressed.shape | |
ratio_orig = ho/wo | |
ratio_comp = hc/wc | |
dim = (wc, hc) | |
if round(ratio_orig, 2) != round(ratio_comp, 2): | |
print("\nImages not of the same dimension. Check input.") | |
exit() | |
# Resize original if the compressed image is smaller | |
elif ho > hc and wo > wc: | |
print("\nResizing original image for analysis...") | |
original = cv2.resize(original, dim) | |
elif ho < hc and wo < wc: | |
print("\nCompressed image has a larger dimension than the original. Check input.") | |
exit() | |
value = PSNR(original, compressed) | |
print("\nPeak Signal-to-Noise Ratio (PSNR) value is", value, "dB") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment