How do I calculate the maximum signal to noise ratio (PSNR) in Python? Is there any library that can calculate PSNR for Image?
-
You can use python ski-image library. Using it you can calculate PSNR Value. – RUC... Jan 17 '19 at 09:44
-
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review – A_A Jan 17 '19 at 10:33
4 Answers
You can use cv2.PSNR like this example:
import cv2
img1 = cv2.imread('img1.bmp')
img2 = cv2.imread('img2.bmp')
psnr = cv2.PSNR(img1, img2)
- 111
- 1
- 2
The steps for calculation of PSNR value of two images:
import math
import cv2
import numpy as np
original = cv2.imread("original.png")
contrast = cv2.imread("photoshopped.png", 1)
def psnr(img1, img2):
mse = np.mean(np.square(np.subtract(img1.astype(np.int16),
img2.astype(np.int16)))
if mse == 0:
return np.Inf
PIXEL_MAX = 255.0
return 20 * math.log10(PIXEL_MAX) - 10 * math.log10(mse)
d = psnr(original, contrast)
print(d)
- 3,590
- 19
- 24
- 27
- 81
- 1
- 2
turn to float first!!!!!!!! turn to float first!!!!!!!! turn to float first!!!!!!!!
def compute_psnr(img1, img2):
img1 = img1.astype(np.float64) / 255.
img2 = img2.astype(np.float64) / 255.
mse = np.mean((img1 - img2) ** 2)
if mse == 0:
return "Same Image"
return 10 * math.log10(1. / mse)
- 51
- 1
- 1
-
Technically, you don't need to convert to float specifically. That is done automatically:
np.mean(np.arange(3)**2) == 1.666.... However, if(img1 - img2)is of dtypenp.uint8, you will of course not be able to store the results of the computation in an 8-bit unsigned integer. – Mateen Ulhaq Aug 11 '21 at 08:34
If you have a replica of your signal (image) that is noise free, you can calculate the correlation coefficient which is directly related to SNR.
See my response here for specific details on determining the correlation coefficient and from that SNR:
In this context there is no "maximum SNR" but will be the SNR for your entire image, meaning the power of your desired signal relative to everything else (distortions).
- 50,942
- 2
- 57
- 135
-
thanks for your reply. I posted that is there have any lib in python that can calculate PSNR?? – Sudip Das Mar 02 '17 at 19:26
-
1I do not know of one that makes it any simpler than that- what I described is what I do in Python, and the approach is very straightforward. – Dan Boschen Mar 02 '17 at 19:29