OpenCV-检查两个图像是否100%相同的最快方法

OpenCV - Fastest method to check if two images are 100% same or not

本文关键字:100% 方法 是否 图像 检查 两个 OpenCV-      更新时间:2023-10-16

这里有很多问题,用来检查两个图像是否"几乎"相似。

我的任务很简单。使用OpenCV,我想知道两个图像是否100%相同。

它们的大小相同,但可以用不同的文件名保存。

您可以使用类似xor运算符的逻辑运算符。如果您使用python,您可以使用以下单行功能:

Python

def is_similar(image1, image2):
    return image1.shape == image2.shape and not(np.bitwise_xor(image1,image2).any())

其中shape是表示矩阵大小的性质,bitwise_xor顾名思义。C++版本可以用类似的方法制作!

C++

请参阅@berak代码。


注意:Python代码适用于任何深度图像(1-D、2-D、3-D等),但C++版本仅适用于2-D图像。你自己很容易把它转换成任何深度的图像。我希望这能给你洞察力!:)

文档:bitwise_xor

编辑C++已删除。感谢@Micka和@berak的评论。

差异之和应为0(对于所有通道):

bool equal(const Mat & a, const Mat & b)
{
    if ( (a.rows != b.rows) || (a.cols != b.cols) )
        return false;
    Scalar s = sum( a - b );
    return (s[0]==0) && (s[1]==0) && (s[2]==0);
}
import cv2
import numpy as np
a = cv2.imread("picture1.png")
b = cv2.imread("picture2.png")
difference = cv2.subtract(a, b)    
result = not np.any(difference)
if result is True:
    print("Pictures are the same")
else:
    print("Pictures are different")

如果它们是相同的文件,但保存在不同的文件名中,则可以检查它们的校验和是否相同。

导入我们需要的包——matplotlib用于绘图,NumPy用于数字处理,cv2用于OpenCV绑定。结构相似性指数方法已经通过scikit图像为我们实现了,所以我们只使用它们的实现

# 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从磁盘上加载图像。我们将使用原始图像、对比度调整后的图像和我们的PS图像

然后我们将图像转换为灰度

# 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/

我已经完成了这项任务。

比较文件大小。比较exif数据。比较第一个"n"字节,其中"n"是128到1024左右。比较最后'n'个字节。比较中间的"n"个字节。比较校验和

@D.Kastier引用了比较两张图像的良好解决方案(https://stackoverflow.com/a/44218701/5734097)但既然你要求最快的方法,我不得不提到硬件加速(尤其是因为你使用的是OpenCV,它支持OpenCL)。为了在GPU/NPU上获得OpenCL的好处,你需要使用UMat而不是Mat。这两种实现之间有一些区别,但在许多情况下,它们可以作为一种替代品。如果你没有GPU/NPU?没问题,因为OpenCV T-API会检测到这一点,而是使用你的CPU。我还没有测试最快的方法,可能有必要在进行比较时上传,以获得良好的收益。以下代码基于:https://stackoverflow.com/a/64022887/1884837

bool areEqual(const cv::UMat& a, const cv::UMat& b)
{
    cv::UMat temp;
    cv::bitwise_xor(a,b,temp);
    return !(cv::countNonZero(temp.reshape(1)));
}
int main() {
    //Read a Mat using imread and upload it to a GPU/NPU device if there is one.
    UMat image0 = imread("00.png").getUMat(cv::ACCESS_READ);
    UMat image1 = imread("01.png").getUMat(cv::ACCESS_READ);
    return areEqual(image0, image1);
}