4
$\begingroup$

How do I calculate the maximum signal to noise ratio (PSNR) in Python? Is there any library that can calculate PSNR for Image?

$\endgroup$
5
$\begingroup$

The steps for calculation of PSNR value of two images:

For details click here

import numpy 
import math
import cv2
original = cv2.imread("original.png")
contrast = cv2.imread("photoshopped.png",1)
def psnr(img1, img2):
    mse = numpy.mean( (img1 - img2) ** 2 )
    if mse == 0:
    return 100
    PIXEL_MAX = 255.0
    return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))

d=psnr(original,contrast)
print(d)
$\endgroup$
  • $\begingroup$ Why return 100 if the MSE == 0? $\endgroup$ – Coda Chang Apr 1 at 6:20
1
$\begingroup$

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:

Noise detection

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).

$\endgroup$
  • $\begingroup$ thanks for your reply. I posted that is there have any lib in python that can calculate PSNR?? $\endgroup$ – Sudip Das Mar 2 '17 at 19:26
  • 1
    $\begingroup$ I 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. $\endgroup$ – Dan Boschen Mar 2 '17 at 19:29
1
$\begingroup$

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)
$\endgroup$
1
$\begingroup$

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)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.