导入我们需要的包——matplotlib 用于绘图,NumPy 用于数值处理,cv2 用于我们的 OpenCV 绑定。 scikit-image 已经为我们实现了结构相似性索引方法,所以我们将使用它们的实现
# import the necessary packages
from skimage.measure import structural_similarity as ssim
import matplotlib.pyplot as plt
import numpy as np
import cv2
然后定义 compare_images 函数,我们将使用它来使用 MSE 和 SSIM 比较两个图像。 mse 函数接受三个参数:imageA 和 imageB,这是我们要比较的两个图像,然后是我们图形的标题。
然后我们计算两个图像之间的 MSE 和 SSIM。
我们还简单地显示与我们正在比较的两个图像相关联的 MSE 和 SSIM。
def mse(imageA, imageB):
# the 'Mean Squared Error' between the two images is the
# sum of the squared difference between the two images;
# NOTE: the two images must have the same dimension
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
# return the MSE, the lower the error, the more "similar"
# the two images are
return err
def compare_images(imageA, imageB, title):
# compute the mean squared error and structural similarity
# index for the images
m = mse(imageA, imageB)
s = ssim(imageA, imageB)
# setup the figure
fig = plt.figure(title)
plt.suptitle("MSE: %.2f, SSIM: %.2f" % (m, s))
# show first image
ax = fig.add_subplot(1, 2, 1)
plt.imshow(imageA, cmap = plt.cm.gray)
plt.axis("off")
# show the second image
ax = fig.add_subplot(1, 2, 2)
plt.imshow(imageB, cmap = plt.cm.gray)
plt.axis("off")
# show the images
plt.show()
使用 OpenCV 从磁盘加载图像。我们将使用原始图像、对比度调整图像和我们的 Photoshop 图像
然后我们将图像转换为灰度
# load the images -- the original, the original + contrast,
# and the original + photoshop
original = cv2.imread("images/jp_gates_original.png")
contrast = cv2.imread("images/jp_gates_contrast.png")
shopped = cv2.imread("images/jp_gates_photoshopped.png")
# convert the images to grayscale
original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
contrast = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY)
shopped = cv2.cvtColor(shopped, cv2.COLOR_BGR2GRAY)
我们将生成一个 matplotlib 图形,一个接一个地循环我们的图像,并将它们添加到我们的绘图中。然后我们的情节就会显示给我们。
最后,我们可以使用 compare_images 函数比较我们的图像。
# initialize the figure
fig = plt.figure("Images")
images = ("Original", original), ("Contrast", contrast), ("Photoshopped", shopped)
# loop over the images
for (i, (name, image)) in enumerate(images):
# show the image
ax = fig.add_subplot(1, 3, i + 1)
ax.set_title(name)
plt.imshow(image, cmap = plt.cm.gray)
plt.axis("off")
# show the figure
plt.show()
# compare the images
compare_images(original, original, "Original vs. Original")
compare_images(original, contrast, "Original vs. Contrast")
compare_images(original, shopped, "Original vs. Photoshopped")
参考-https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/