|
1 |
| -import numpy as np |
| 1 | +""" |
| 2 | + Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio |
| 3 | + Soruce: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/ |
| 4 | +""" |
| 5 | + |
2 | 6 | import math
|
| 7 | + |
3 | 8 | import cv2
|
| 9 | +import numpy as np |
4 | 10 |
|
5 |
| -def Representational(r,g,b): |
6 |
| - return (0.299*r+0.287*g+0.114*b) |
| 11 | +def psnr(original, contrast): |
| 12 | + mse = np.mean((original - contrast) ** 2) |
| 13 | + if mse == 0: |
| 14 | + return 100 |
| 15 | + PIXEL_MAX = 255.0 |
| 16 | + PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) |
| 17 | + return PSNR |
7 | 18 |
|
8 |
| -def calculate(img): |
9 |
| - b,g,r = cv2.split(img) |
10 |
| - pixelAt = Representational(r,g,b) |
11 |
| - return pixelAt |
12 | 19 |
|
13 | 20 | def main():
|
14 |
| - |
15 |
| - #Loading images (orignal image and compressed image) |
16 |
| - orignal_image = cv2.imread('orignal_image.png',1) |
17 |
| - compressed_image = cv2.imread('compressed_image.png',1) |
18 | 21 |
|
19 |
| - #Getting image height and width |
20 |
| - height,width = orignal_image.shape[:2] |
| 22 | + # Loading images (original image and compressed image) |
| 23 | + original = cv2.imread('original_image.png') |
| 24 | + contrast = cv2.imread('compressed_image.png', 1) |
21 | 25 |
|
22 |
| - orignalPixelAt = calculate(orignal_image) |
23 |
| - compressedPixelAt = calculate(compressed_image) |
| 26 | + original2 = cv2.imread('PSNR-example-base.png') |
| 27 | + contrast2 = cv2.imread('PSNR-example-comp-10.jpg', 1) |
24 | 28 |
|
25 |
| - diff = orignalPixelAt - compressedPixelAt |
26 |
| - error = np.sum(np.abs(diff) ** 2) |
27 |
| - |
28 |
| - error = error/(height*width) |
29 |
| - |
30 |
| - #MSR = error_sum/(height*width) |
31 |
| - PSNR = -(10*math.log10(error/(255*255))) |
32 |
| - |
33 |
| - print("PSNR value is {}".format(PSNR)) |
| 29 | + # Value expected: 29.73dB |
| 30 | + print("-- First Test --") |
| 31 | + print(f"PSNR value is {psnr(original, contrast)} dB") |
| 32 | + |
| 33 | + # # Value expected: 31.53dB (Wikipedia Example) |
| 34 | + print("\n-- Second Test --") |
| 35 | + print(f"PSNR value is {psnr(original2, contrast2)} dB") |
34 | 36 |
|
35 | 37 |
|
36 | 38 | if __name__ == '__main__':
|
37 |
| - main() |
38 |
| - |
| 39 | + main() |
0 commit comments