Skip to content

Instantly share code, notes, and snippets.

@AdamDimech
Created February 11, 2021 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamDimech/dab281b56b90dae78d2544a9508c36a4 to your computer and use it in GitHub Desktop.
Save AdamDimech/dab281b56b90dae78d2544a9508c36a4 to your computer and use it in GitHub Desktop.
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()
@Digitall123
Copy link

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

usage: ipykernel_launcher.py [-h] -o ORIGINAL -c COPY
ipykernel_launcher.py: 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