欢迎关注博主的公众号:happyGirl的异想世界。有更多干货还有技术讨论群哦~
psnr是“Peak Signal to Noise Ratio”的缩写,即峰值信噪比,是一种评价图像的客观标准,它具有局限性,一般是用于最大值信号和背景噪音之间的一个工程项目。
from PIL import Image import numpy import math 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)) img1=Image.open('1.png') img2=Image.open('2.jpg') i1_array = numpy.array(img1) i2_array = numpy.array(img2) r12=psnr(i1_array,i2_array) print(r12)SSIM(Structural SIMilarity),结构相似性,是一种衡量两幅图像相似度的指标。该指标首先由德州大学奥斯丁分校的图像和视频工程实验室(Laboratory for Image and Video Engineering)提出。
SSIM使用的两张图像中,一张为未经压缩的无失真图像,另一张为失真后的图像。
import cv2 import numpy as np def ssim(img1, img2): C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 img1 = img1.astype(np.float64) img2 = img2.astype(np.float64) kernel = cv2.getGaussianKernel(11, 1.5) window = np.outer(kernel, kernel.transpose()) mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5] mu1_sq = mu1 ** 2 mu2_sq = mu2 ** 2 mu1_mu2 = mu1 * mu2 sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) return ssim_map.mean() def calculate_ssim(img1, img2): '''calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255] ''' if not img1.shape == img2.shape: raise ValueError('Input images must have the same dimensions.') if img1.ndim == 2: return ssim(img1, img2) elif img1.ndim == 3: if img1.shape[2] == 3: ssims = [] for i in range(3): ssims.append(ssim(img1, img2)) return np.array(ssims).mean() elif img1.shape[2] == 1: return ssim(np.squeeze(img1), np.squeeze(img2)) else: raise ValueError('Wrong input image dimensions.') img1 = cv2.imread("1.png", 0) img2 = cv2.imread("2.jpg", 0) img3 = cv2.imread("3.jpg", 0) img4 = cv2.imread("4.png", 0) img1 = np.array(img1) img2 = np.array(img2) img3 = np.array(img3) img4 = np.array(img4) ss = calculate_ssim(img2, img3) print(ss)
ssim代码参考:https://www.jb51.net/article/176717.htm
