Python/analysis/compression_analysis/psnr.py

41 lines
1.2 KiB
Python
Raw Normal View History

"""
Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
Soruce: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
"""
2018-10-19 12:48:28 +00:00
import math
import os
2018-10-19 12:48:28 +00:00
import cv2
import numpy as np
2018-10-19 12:48:28 +00:00
def psnr(original, contrast):
mse = np.mean((original - contrast) ** 2)
if mse == 0:
return 100
PIXEL_MAX = 255.0
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
return PSNR
2018-10-19 12:48:28 +00:00
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
# Loading images (original image and compressed image)
original = cv2.imread(os.path.join(dir_path, 'original_image.png'))
contrast = cv2.imread(os.path.join(dir_path, 'compressed_image.png'), 1)
2018-10-19 12:48:28 +00:00
original2 = cv2.imread(os.path.join(dir_path, 'PSNR-example-base.png'))
contrast2 = cv2.imread(os.path.join(dir_path, 'PSNR-example-comp-10.jpg'), 1)
2018-10-19 12:48:28 +00:00
# Value expected: 29.73dB
print("-- First Test --")
print(f"PSNR value is {psnr(original, contrast)} dB")
# # Value expected: 31.53dB (Wikipedia Example)
print("\n-- Second Test --")
print(f"PSNR value is {psnr(original2, contrast2)} dB")
2018-10-19 12:48:28 +00:00
if __name__ == '__main__':
main()