Skip to content

Instantly share code, notes, and snippets.

Created February 11, 2021 23:36
What would you like to do?
Quantitatively check the quality of a compressed image by calculating the Peak Signal-to-Noise Ratio (PSNR) between two images. More info at
#!/usr/bin/env python
from math import log10, sqrt
import cv2
import numpy as np
import argparse
# Based on
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.")
# 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.")
value = PSNR(original, compressed)
print("\nPeak Signal-to-Noise Ratio (PSNR) value is", value, "dB")
if __name__ == '__main__':
Copy link

Hi! Thanks for the code for help! But I am getting this error

usage: [-h] -o ORIGINAL -c COPY error: the following arguments are required: -o/--original, -c/--copy
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment