2018-11-05 17:19:08 +00:00
|
|
|
"""
|
2020-06-16 08:09:19 +00:00
|
|
|
Peak signal-to-noise ratio - PSNR
|
|
|
|
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
|
|
|
|
Source:
|
|
|
|
https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python
|
2018-11-05 17:19:08 +00:00
|
|
|
"""
|
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
import math
|
2018-12-26 13:06:34 +00:00
|
|
|
import os
|
2018-11-05 17:19:08 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
import cv2
|
2018-11-05 17:19:08 +00:00
|
|
|
import numpy as np
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2021-10-26 10:29:27 +00:00
|
|
|
def psnr(original: float, contrast: float) -> float:
|
2018-11-05 17:19:08 +00:00
|
|
|
mse = np.mean((original - contrast) ** 2)
|
|
|
|
if mse == 0:
|
|
|
|
return 100
|
2022-10-12 22:54:20 +00:00
|
|
|
PIXEL_MAX = 255.0 # noqa: N806
|
|
|
|
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) # noqa: N806
|
2018-11-05 17:19:08 +00:00
|
|
|
return PSNR
|
2018-10-19 12:48:28 +00:00
|
|
|
|
|
|
|
|
2021-10-26 10:29:27 +00:00
|
|
|
def main() -> None:
|
2018-12-26 13:06:34 +00:00
|
|
|
dir_path = os.path.dirname(os.path.realpath(__file__))
|
2018-11-05 17:19:08 +00:00
|
|
|
# Loading images (original image and compressed image)
|
2019-10-05 05:14:13 +00:00
|
|
|
original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png"))
|
|
|
|
contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1)
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png"))
|
|
|
|
contrast2 = cv2.imread(
|
|
|
|
os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1
|
|
|
|
)
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2018-11-05 17:19:08 +00:00
|
|
|
# Value expected: 29.73dB
|
|
|
|
print("-- First Test --")
|
|
|
|
print(f"PSNR value is {psnr(original, contrast)} dB")
|
2018-12-26 13:06:34 +00:00
|
|
|
|
2018-11-05 17:19:08 +00:00
|
|
|
# # 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
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2018-11-05 17:19:08 +00:00
|
|
|
main()
|