import numpy as np import cv2 def ssim(img1, img2): # Set constants C1 = (0.01 * 255) ** 2 C2 = (0.03 * 255) ** 2 # Convert the images to grayscale img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # Compute mean, variance and covariance img1_mean = cv2.mean(img1)[0] img2_mean = cv2.mean(img2)[0] img1_var = cv2.meanStdDev(img1)[1]**2 img2_var = cv2.meanStdDev(img2)[1]**2 img12_covar = np.mean((img1 - img1_mean) * (img2 - img2_mean)) # Compute SSIM numerator = (2 * img1_mean * img2_mean + C1) * (2 * img12_covar + C2) denominator = (img1_mean ** 2 + img2_mean ** 2 + C1) * (img1_var + img2_var + C2) return numerator / denominator # Load the images img1 = cv2.imread('0.jpg') img2 = cv2.imread('2.jpg') # Compute SSIM ssim_value = ssim(img1, img2) print('SSIM value:', ssim_value)这串代码加上调整img2和img1尺寸一致
时间: 2024-01-26 07:03:54 浏览: 138
可以使用cv2.resize()函数来调整图像尺寸,代码如下:
```
import numpy as np
import cv2
def ssim(img1, img2):
# Set constants
C1 = (0.01 * 255) ** 2
C2 = (0.03 * 255) ** 2
# Resize img2 to match img1 shape
img2 = cv2.resize(img2, img1.shape[:2][::-1])
# Convert the images to grayscale
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Compute mean, variance and covariance
img1_mean = cv2.mean(img1)[0]
img2_mean = cv2.mean(img2)[0]
img1_var = cv2.meanStdDev(img1)[1]**2
img2_var = cv2.meanStdDev(img2)[1]**2
img12_covar = np.mean((img1 - img1_mean) * (img2 - img2_mean))
# Compute SSIM
numerator = (2 * img1_mean * img2_mean + C1) * (2 * img12_covar + C2)
denominator = (img1_mean ** 2 + img2_mean ** 2 + C1) * (img1_var + img2_var + C2)
return numerator / denominator
# Load the images
img1 = cv2.imread('0.jpg')
img2 = cv2.imread('2.jpg')
# Compute SSIM
ssim_value = ssim(img1, img2)
print('SSIM value:', ssim_value)
```
注意,使用cv2.resize()函数时需要将img1的shape切片取前两个元素并反转,以便将宽和高作为resize()函数的参数。
阅读全文