如何使用java比较图像的相似性

时间:2011-12-19 21:39:07

标签: java image image-processing

最近我有机会使用Image Processing Technologies作为我的一个项目的一部分,我的任务是在给出新图像时从图像存储中找到匹配的图像。我用Google搜索“如何使用java比较图像”开始我的项目,我收到了一些关于找到两个图像的相似性的好文章。几乎所有这些都基于四个基本步骤,它们是:

1.Locating the Region of Interest (Where the Objects appear in the given image),
2.Re-sizing the ROIs in to a common size,
3.Substracting ROIs,
4.Calculating the Black and White Ratio of the resultant image after subtraction.

虽然这听起来是比较图像的好算法,但在我的项目中使用 JAI 实现它需要相当长的时间。因此,我必须找到另一种方法。

有什么建议吗?

3 个答案:

答案 0 :(得分:10)

    **// This API will compare two image file //
// return true if both image files are equal else return false//**
public static boolean compareImage(File fileA, File fileB) {        
    try {
        // take buffer data from botm image files //
        BufferedImage biA = ImageIO.read(fileA);
        DataBuffer dbA = biA.getData().getDataBuffer();
        int sizeA = dbA.getSize();                      
        BufferedImage biB = ImageIO.read(fileB);
        DataBuffer dbB = biB.getData().getDataBuffer();
        int sizeB = dbB.getSize();
        // compare data-buffer objects //
        if(sizeA == sizeB) {
            for(int i=0; i<sizeA; i++) { 
                if(dbA.getElem(i) != dbB.getElem(i)) {
                    return false;
                }
            }
            return true;
        }
        else {
            return false;
        }
    } 
    catch (Exception e) { 
        System.out.println("Failed to compare image files ...");
        return  false;
    }
}

答案 1 :(得分:6)

根据图像的不同,你可以做这样的事情(伪代码)。这是非常原始的,但应该非常有效。您可以通过采用随机或图案像素而不是每个像素来加快速度。

for x = 0 to image.size:
    for y = 0 to image.size:
        diff += abs(image1.get(x,y).red - image2.get(x,y).red)
        diff += abs(image1.get(x,y).blue - image2.get(x,y).blue)
        diff += abs(image1.get(x,y).green - image2.get(x,y).green)
    end
end

return ((float)(diff)) / ( x * y * 3)

答案 2 :(得分:6)

此API将比较两个图像文件并返回相似百分比

public float compareImage(File fileA, File fileB) {

    float percentage = 0;
    try {
        // take buffer data from both image files //
        BufferedImage biA = ImageIO.read(fileA);
        DataBuffer dbA = biA.getData().getDataBuffer();
        int sizeA = dbA.getSize();
        BufferedImage biB = ImageIO.read(fileB);
        DataBuffer dbB = biB.getData().getDataBuffer();
        int sizeB = dbB.getSize();
        int count = 0;
        // compare data-buffer objects //
        if (sizeA == sizeB) {

            for (int i = 0; i < sizeA; i++) {

                if (dbA.getElem(i) == dbB.getElem(i)) {
                    count = count + 1;
                }

            }
            percentage = (count * 100) / sizeA;
        } else {
            System.out.println("Both the images are not of same size");
        }

    } catch (Exception e) {
        System.out.println("Failed to compare image files ...");
    }
    return percentage;
}