How to compare images for similarity using java

后端 未结 3 1773
梦谈多话
梦谈多话 2020-12-01 14:19

Recently I got an opportunity to work with Image Processing Technologies as a part of one of my projects and my task was to find matching images from an image store when a n

3条回答
  •  庸人自扰
    2020-12-01 15:04

    This API will compare two image file and return the percentage of similarity

    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;
    }
    

提交回复
热议问题