比较BGR图像是否完全相同

Compare if BGR image is exactly the same

本文关键字:是否 BGR 图像 比较      更新时间:2023-10-16

我正在尝试编写代码以找出两个图像是否相同。我能够将图像读为BGR,并能够从另一个中减去图像。我需要进行检查,看看差异是否仅包含零。我知道有一个称为countNonZero的函数,但仅在单个通道上起作用,而不是3个通道。我的解决方案是循环浏览整个矩阵并检查一切是否为零,但这太慢了。有没有有效的检查方法?这是我下面的代码。

int main(int argc, char** argv)
{
  if(argc != 3)
  {
    printf("usage: DisplayImage.out <testImg.png> <copy.png>n");
    return -1; 
  }
  Mat image;
  Mat copy;
  Mat output;
  image = imread(argv[1], 1); 
  copy = imread(argv[2], 1); 
  absdiff(image, copy, output);
  if(countNonZero(output) == 0)
  {
    cout << "Same" << endl;
  }
  else
  {
    cout << "Different" << endl;
  }
  imshow("outut", output);
  waitKey();
  return 0;
}

您可以做到这一点:

Mat diff_im = image - copy;
double s = cv::sum(diff_im)[0];

您也可以使用norm类型NORM_L2

使用OPENCV的norm()函数
double rst = cv::norm(img1, img2, cv::NORM_L2);

如果图像完全相同,则结果将为零。

越接近零。