c# 是判断两个图片是否为一张图片

  没有别的办法,只能靠数据流读取图片再转化为字节数组进行比对。分享一下。


private bool Same(Image image1, Image image2)

        {
            MemoryStream ms1 = new MemoryStream();
            MemoryStream ms2 = new MemoryStream();

            image1.Save(ms1, System.Drawing.Imaging.ImageFormat.Bmp);
            image2.Save(ms2, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] im1 = ms1.GetBuffer();
            byte[] im2 = ms2.GetBuffer();
            if (im1.Length != im2.Length)
                return false;
            else
            {
                for (int i = 0; i < im1.Length; i++)
                    if (im1[i] != im2[i])
                        return false;
            }
            return true;
        }
要实现两张图片的直方图对比,你需要执行以下步骤: 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、付费专栏及课程。

余额充值