Java对比2张图片的相识度

(图像大小不一致缺陷) 方法1图像处理库 java.awt 和 javax.imageio,通过将图片转换为灰度图像,然后比较像素值来计算相似度

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageSimilarityUtils {

    /**
     * 计算两张图片的相似度
     * @param imagePath1 第一张图片的路径
     * @param imagePath2 第二张图片的路径
     * @return 相似度,范围从 0 到 1,值越接近 1 表示越相似
     */
    public static double compareImages(String imagePath1, String imagePath2) {
        try {
            // 读取两张图片
            BufferedImage image1 = ImageIO.read(new File(imagePath1));
            BufferedImage image2 = ImageIO.read(new File(imagePath2));

            // 调整图片大小为相同尺寸
            int width = Math.min(image1.getWidth(), image2.getWidth());
            int height = Math.min(image1.getHeight(), image2.getHeight());

            // 统计相同像素的数量
            int samePixelCount = 0;
            int totalPixelCount = width * height;

            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    // 获取两张图片对应位置的像素值
                    int rgb1 = image1.getRGB(x, y);
                    int rgb2 = image2.getRGB(x, y);

                    // 转换为灰度值
                    int gray1 = getGrayValue(rgb1);
                    int gray2 = getGrayValue(rgb2);

                    // 比较灰度值
                    if (gray1 == gray2) {
                        samePixelCount++;
                    }
                }
            }

            // 计算相似度
            return (double) samePixelCount / totalPixelCount;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将 RGB 值转换为灰度值
     * @param rgb RGB 值
     * @return 灰度值
     */
    private static int getGrayValue(int rgb) {
        Color color = new Color(rgb);
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        return (r + g + b) / 3;
    }

    public static void main(String[] args) {
        String imagePath1 = "C:\\Users\\Downloads\\20250313-111643.jpg";
        String imagePath2 = "C:\\Users\\Downloads\\20250313-111638.jpg";
        double similarity = compareImages(imagePath1, imagePath2);
        System.out.printf("两张图片的相似度为: %.2f%%\n", similarity * 100);
    }
}

(解决图像大小不一致对比)方法2:使用感知哈希算法(Perceptual Hash Algorithm),其中比较常用的是均值哈希(Average Hash)和感知哈希(pHash)

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageSimilarityUtils {

    /**
     * 计算两张图片的相似度
     *
     * @param imagePath1 第一张图片的路径
     * @param imagePath2 第二张图片的路径
     * @return 相似度,范围从 0 到 1,值越接近 1 表示越相似
     */
    public static double compareImages(String imagePath1, String imagePath2) {
        try {
            // 计算两张图片的哈希值
            String hash1 = calculateAverageHash(imagePath1);
            String hash2 = calculateAverageHash(imagePath2);

            // 计算汉明距离
            int hammingDistance = hammingDistance(hash1, hash2);

            // 计算相似度
            return 1 - (double) hammingDistance / hash1.length();
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 计算图片的均值哈希值
     *
     * @param imagePath 图片的路径
     * @return 图片的均值哈希值
     * @throws IOException 读取图片时可能抛出的异常
     */
    private static String calculateAverageHash(String imagePath) throws IOException {
        // 读取图片
        BufferedImage image = ImageIO.read(new File(imagePath));

        // 调整图片大小为 8x8
        BufferedImage resizedImage = resizeImage(image, 8, 8);

        // 转换为灰度图像
        int[] grayPixels = convertToGray(resizedImage);

        // 计算灰度平均值
        int average = calculateAverage(grayPixels);

        // 生成哈希值
        StringBuilder hash = new StringBuilder();
        for (int pixel : grayPixels) {
            if (pixel >= average) {
                hash.append("1");
            } else {
                hash.append("0");
            }
        }

        return hash.toString();
    }

    /**
     * 调整图片大小
     *
     * @param originalImage 原始图片
     * @param width         调整后的宽度
     * @param height        调整后的高度
     * @return 调整大小后的图片
     */
    private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        resizedImage.getGraphics().drawImage(originalImage, 0, 0, width, height, null);
        return resizedImage;
    }

    /**
     * 将图片转换为灰度图像
     *
     * @param image 原始图片
     * @return 灰度像素数组
     */
    private static int[] convertToGray(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        int[] grayPixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                Color color = new Color(rgb);
                int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
                grayPixels[y * width + x] = gray;
            }
        }

        return grayPixels;
    }

    /**
     * 计算像素数组的平均值
     *
     * @param pixels 像素数组
     * @return 平均值
     */
    private static int calculateAverage(int[] pixels) {
        int sum = 0;
        for (int pixel : pixels) {
            sum += pixel;
        }
        return sum / pixels.length;
    }

    /**
     * 计算两个字符串的汉明距离
     *
     * @param s1 第一个字符串
     * @param s2 第二个字符串
     * @return 汉明距离
     */
    private static int hammingDistance(String s1, String s2) {
        int distance = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                distance++;
            }
        }
        return distance;
    }

    public static void main(String[] args) {
        String imagePath1 = "C:\\Users\\Downloads\\20250313-111643.jpg";
        String imagePath2 = "C:\\Users\\Downloads\\20250313-111638.jpg";
        double similarity = compareImages(imagePath1, imagePath2);
        System.out.printf("两张图片的相似度为: %.2f%%\n", similarity * 100);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值