Como julgar se duas imagens são iguais em java

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageCompare {
    
    
    

    public static void main(String[] args) throws IOException {
    
    
        
        File file1 = new File("image1.png");
        File file2 = new File("image2.png");
        
        BufferedImage img1 = ImageIO.read(file1);
        BufferedImage img2 = ImageIO.read(file2);
        
        int width1 = img1.getWidth();
        int width2 = img2.getWidth();
        int height1 = img1.getHeight();
        int height2 = img2.getHeight();
        
        if (width1 != width2 || height1 != height2) {
    
    
            System.out.println("两张图片尺寸不同,肯定不相同");
        } else {
    
    
            long diff = 0;
            for (int y = 0; y < height1; y++) {
    
    
                for (int x = 0; x < width1; x++) {
    
    
                    int rgb1 = img1.getRGB(x, y);
                    int rgb2 = img2.getRGB(x, y);
                    int r1 = (rgb1 >> 16) & 0xff;
                    int g1 = (rgb1 >> 8) & 0xff;
                    int b1 = (rgb1) & 0xff;
                    int r2 = (rgb2 >> 16) & 0xff;
                    int g2 = (rgb2 >> 8) & 0xff;
                    int b2 = (rgb2) & 0xff;
                    diff += Math.abs(r1 - r2);
                    diff += Math.abs(g1 - g2);
                    diff += Math.abs(b1 - b2);
                }
            }
            double n = width1 * height1 * 3;
            double p = diff / n / 255.0;
            if (p < 0.1) {
    
    
                System.out.println("两张图片非常相似");
            } else {
    
    
                System.out.println("两张图片不相似");
            }
        }
    }

}

Este código lê os dados de pixel de duas imagens e os compara. Se a diferença entre os valores de pixel for menor que 0,1, julga-se que as duas imagens são muito semelhantes, caso contrário, não são. Esse método de comparação não é muito rigoroso, pois compara apenas a diferença de valores de pixel, sem levar em conta fatores como semântica e características da imagem. Se você precisar comparar com mais precisão se duas imagens são iguais, poderá usar alguns algoritmos de processamento de imagem e extração de recursos, como bibliotecas de código aberto, como OpenCV

Acho que você gosta

Origin blog.csdn.net/weixin_42456784/article/details/129929297
Recomendado
Clasificación