使用 java 比较图像的相似性

Compare images for similarity using java

我想检查两张图片之间的相似度: to

使用下面的代码,我得到差异百分比-->8.132336061764388。 首先,我将图像调整为相同大小,然后使用比较方法。

如果不是 none 相似度,我预计会有很小的相似度。相似性检查中有什么不正确的地方?还有其他精确的方法吗?

public static void compare(BufferedImage imgA, BufferedImage imgB) {
// Assigning dimensions to image
int width1 = imgA.getWidth();
int width2 = imgB.getWidth();
int height1 = imgA.getHeight();
int height2 = imgB.getHeight();

// Checking whether the images are of same size or
// not
if ((width1 != width2) || (height1 != height2))

  // Display message straightaway
  System.out.println("Error: Images dimensions mismatch");
else {

  long difference = 0;

  // treating images likely 2D matrix

  // Outer loop for rows(height)
  for (int y = 0; y < height1; y++) {

    // Inner loop for columns(width)
    for (int x = 0; x < width1; x++) {

      int rgbA = imgA.getRGB(x, y);
      int rgbB = imgB.getRGB(x, y);
      int redA = (rgbA >> 16) & 0xff;
      int greenA = (rgbA >> 8) & 0xff;
      int blueA = (rgbA) & 0xff;
      int redB = (rgbB >> 16) & 0xff;
      int greenB = (rgbB >> 8) & 0xff;
      int blueB = (rgbB) & 0xff;

      difference += Math.abs(redA - redB);
      difference += Math.abs(greenA - greenB);
      difference += Math.abs(blueA - blueB);
    }
  }

  double total_pixels = width1 * height1 * 3;

  double avg_different_pixels
          = difference / total_pixels;

  double percentage
          = (avg_different_pixels / 255) * 100;

  // Lastly print the difference percentage
  System.out.println("Difference Percentage-->"
          + percentage);
}

}

嗯,首先,我们人类甚至不同意什么是“相似”:它只是形状相同吗?甚至相同的颜色但不同的标记?外观相同但内部电路不同?

话虽如此,对于计算机视觉来说,事情要复杂得多。同样,在计算机视觉中,有很多方法可以判断某物是否“在某种程度上”相似:直方图、角点、边缘、特征等...

查看 Checking images for similarity with OpenCV 了解有关该主题的介绍。

在您的情况下,您获得的“相似度”数字完全基于精确的像素表示,因此对于缩放图像是明智的。此外,请记住 缩放 图像是一种改变像素组成的变换。特别是,您使用某些算法 adding/removing 像素,从而在一定程度上保留了图像的某些高级特征。

如果你想检测两张图片之间的相似度,你必须首先确定什么与你相似,然后你可以结合多种技术来达到你的结果。 OpenCV 提供了良好而坚实的基础。