Python calculates the PSNR value of two images
This article mainly records how to use python to solve the PSNR value of two graphs.
Table of contents
1. PSNR solution formula
(1) The mathematical expression for calculating MSE for a three-channel RGB image is: the
specific code is:
# compute MSE
mse = np.mean((img1/1.0-img2/1.0)**2)
(2) Calculate PSNR after obtaining MSE, the specific mathematical expression is:
the specific code is:
psnr1=20*math.log10(255/math.sqrt(mse))
Another way is to normalize the pixel value, and then solve the PSNR value:
mse = np.mean((img1/255.0-img2/255.0)**2)
psnr2=20*math.log10(1/math.sqrt(mse))
2. Complete PSNR solution code
The full code looks like this:
import cv2
import math
import numpy
def psnr1(img1, img2):
# compute mse
# mse = np.mean((img1-img2)**2)
mse = numpy.mean((img1 / 1.0 - img2 / 1.0) ** 2)
# compute psnr
if mse < 1e-10:
return 100
psnr1 = 20 * math.log10(255 / math.sqrt(mse))
return psnr1
def psnr2(img1, img2):
mse = numpy.mean((img1 / 255.0 - img2 / 255.0) ** 2)
if mse < 1e-10:
return 100
psnr2 = 20 * math.log10(1 / math.sqrt(mse))
return psnr2
imag1 = cv2.imread("./image/original_image/Lena.bmp")
print("imag1.shap: {}".format(imag1.shape))
imag2 = cv2.imread("./image/embedded_image/Lena.bmp_embed_image.bmp")
print("imag1.shap: {}".format(imag2.shape))
image_size = [512, 512] #将图像转化为512*512大小的尺寸
imag1 = cv2.resize(imag1, image_size, interpolation=cv2.INTER_CUBIC)
imag1 = cv2.cvtColor(imag1, cv2.COLOR_BGR2GRAY)#将图像转化为灰度图像,不是必须转,也可以使用原始的彩色图像
imag2 = cv2.resize(imag2, image_size, interpolation=cv2.INTER_CUBIC)
imag2 = cv2.cvtColor(imag2, cv2.COLOR_BGR2GRAY)#将图像转化为灰度图像,不是必须转,也可以使用原始的彩色图像
res1 = psnr1(imag1, imag2)
print("res1:", res1)
res2 = psnr2(imag1, imag2)
print("res2:", res2)
3. Calculation result display
4. References
Reference link: Calculate the peak signal-to-noise ratio PSNR of two images with Python .