计算两个图像的结构相似度,代码
时间: 2023-10-04 12:06:03 浏览: 119
以下是Python代码实现图像结构相似度的计算:
```python
import cv2
import numpy as np
def calculate_ssim(img1, img2, k1=0.01, k2=0.03, L=255):
# Compute mean, variance and covariance of img1 and img2
mu1 = cv2.GaussianBlur(img1, (11, 11), 1.5)
mu2 = cv2.GaussianBlur(img2, (11, 11), 1.5)
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = cv2.GaussianBlur(img1 ** 2, (11, 11), 1.5) - mu1_sq
sigma2_sq = cv2.GaussianBlur(img2 ** 2, (11, 11), 1.5) - mu2_sq
sigma12 = cv2.GaussianBlur(img1 * img2, (11, 11), 1.5) - mu1_mu2
# Compute SSIM
C1 = (k1 * L) ** 2
C2 = (k2 * L) ** 2
ssim = (2 * mu1_mu2 + C1) * (2 * sigma12 + C2)
denom = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
ssim /= denom
return np.mean(ssim)
# Load images
img1 = cv2.imread('img1.jpg')
img2 = cv2.imread('img2.jpg')
# Convert images to grayscale
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Calculate SSIM
ssim = calculate_ssim(img1_gray, img2_gray)
# Print SSIM
print("SSIM:", ssim)
```
其中,calculate_ssim函数用于计算两个图像的结构相似度,img1和img2分别为输入的两个图像,k1和k2是常数,L是像素值的范围(例如,对于8位图像,L=255),函数返回两个图像的结构相似度。在代码中,我们首先加载两个图像,然后将它们转换为灰度图像,并调用calculate_ssim函数计算它们的结构相似度。最后,我们将计算得到的结构相似度打印出来。