java图片对比 实现_java利用直方图实现图片对比

需求

实现两张图对比,找出其中不同的部分。

分析

首先将大图切片,分成许多小图片。然后进行逐个对比,并设定相似度阈值,判断是否是相同。最后整理,根据生成数组标记不同部分。如果切片足够小,便越能精确找出不同点。

本例使用1024x1024图片,切片大小为32x32。

实现

import java.awt.Color;

import java.awt.image.BufferedImage;

import java.io.File;

import javax.imageio.ImageIO;

public class PicTest {

public final static int THRESHOLD = 90;//阈值百分比

public static void main(String[] args) throws Exception {

//用于记录不同点

int[][] comparyArray = new int[32][32];

//两张图片

BufferedImage img1 = ImageIO.read(new File("G:\\1.jpg"));

BufferedImage img2 = ImageIO.read(new File("G:\\2.jpg"));

//两张图片的切片

BufferedImage img1Sub;

BufferedImage img2Sub;

float percent;

//双循环用来取图片的切片坐标

for(int i = 0;i<32;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现两张图片直方图对比,你需要执行以下步骤: 1. 读取两张图片并将它们转换为灰度图像。 2. 将两张图像的灰度值分别统计到两个直方图中。 3. 对两个直方图进行归一化处理,使得它们的和为1。 4. 计算两个直方图之间的距离,可以使用欧几里得距离或者其他的距离度量方法。 5. 根据计算出的距离值,可以判断两张图像的相似度。 下面是一个示例代码,演示如何实现两张图片直方图对比: ```csharp private void CompareHistograms(string imagePath1, string imagePath2) { // 读取两张图片并将它们转换为灰度图像 Bitmap bmp1 = new Bitmap(imagePath1); Bitmap bmp2 = new Bitmap(imagePath2); Bitmap gray1 = Grayscale(bmp1); Bitmap gray2 = Grayscale(bmp2); // 将两张图像的灰度值分别统计到两个直方图中 int[] hist1 = Histogram(gray1); int[] hist2 = Histogram(gray2); // 对两个直方图进行归一化处理 Normalize(hist1); Normalize(hist2); // 计算两个直方图之间的距离 double distance = Distance(hist1, hist2); // 输出结果 Console.WriteLine("Distance: " + distance); } // 将图片转换为灰度图像 private Bitmap Grayscale(Bitmap bmp) { Bitmap gray = new Bitmap(bmp.Width, bmp.Height); for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color color = bmp.GetPixel(x, y); int grayValue = (int)(color.R * 0.299 + color.G * 0.587 + color.B * 0.114); gray.SetPixel(x, y, Color.FromArgb(grayValue, grayValue, grayValue)); } } return gray; } // 计算直方图 private int[] Histogram(Bitmap bmp) { int[] hist = new int[256]; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color color = bmp.GetPixel(x, y); int grayValue = color.R; hist[grayValue]++; } } return hist; } // 归一化直方图 private void Normalize(int[] hist) { int sum = 0; for (int i = 0; i < hist.Length; i++) { sum += hist[i]; } for (int i = 0; i < hist.Length; i++) { hist[i] = (int)(hist[i] * 1.0 / sum * 100); } } // 计算直方图距离 private double Distance(int[] hist1, int[] hist2) { double distance = 0; for (int i = 0; i < hist1.Length; i++) { distance += Math.Pow(hist1[i] - hist2[i], 2); } distance = Math.Sqrt(distance); return distance; } ``` 在上面的示例代码中,Grayscale方法将一张彩色图像转换为灰度图像,Histogram方法计算灰度直方图,Normalize方法对直方图进行归一化处理,Distance方法计算两个直方图之间的距离。最后,你可以调用CompareHistograms方法,传入两张图片的路径,即可计算它们的直方图距离并输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值