一、安装包
<PackageReference Include="OpenCvSharp4" Version="4.10.0.20241108" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.10.0.20241108" />
二、准备两张图片
三、编写代码
using OpenCvSharp;
using System;
using System.Diagnostics;
using System.IO;
using static OpenCvSharp.FileStorage;
using static System.Net.Mime.MediaTypeNames;
namespace OpenCvSharpDemo
{
internal class Program
{
static void Main(string[] args)
{
Compare();
}
static void Compare()
{
var path1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images/A1.png");
var path2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images/A2.png");
// 读取两张图片
Mat image1 = Cv2.ImRead(path1, ImreadModes.Color);
Mat image2 = new Mat();
Cv2.Resize(Cv2.ImRead(path2, ImreadModes.Color), image2, new OpenCvSharp.Size(image1.Size().Width, image1.Size().Height));
if (image1.Empty() || image2.Empty())
{
Console.WriteLine("无法正确读取图片,请检查图片路径是否正确。");
return;
}
// 确保两张图片尺寸一致,如果不一致可以进行调整(这里简单示例假设尺寸相同)
if (image1.Size() != image2.Size())
{
Console.WriteLine("两张图片尺寸不一致,请先处理为相同尺寸。");
return;
}
// 计算两张图片像素差值(逐像素相减)
Mat diff = new Mat();
Cv2.Absdiff(image1, image2, diff);
// 将差异图像转换为灰度图(方便后续阈值处理等操作)
Mat grayDiff = new Mat();
Cv2.CvtColor(diff, grayDiff, ColorConversionCodes.BGR2GRAY);
//膨胀3次
var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5));
Cv2.Dilate(grayDiff, grayDiff, kernel, null, 3);
// 应用阈值,将差异明显的地方凸显出来,这里阈值可以根据实际情况调整
Mat thresholded = new Mat();
Cv2.Threshold(grayDiff, thresholded, 30, 255, ThresholdTypes.Binary);
// 查找轮廓,轮廓所在区域就是不同之处
Point[][] contours;
HierarchyIndex[] hierarchy;
Cv2.FindContours(thresholded, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
// 在原始图片(这里选择image1)上绘制出不同之处的轮廓(标记为红色)
for (int i = 0; i < contours.Length; i++)
{
Cv2.DrawContours(image1, contours, i, new Scalar(0, 0, 255), 2);
}
// 显示标记出不同之处的图片
Cv2.ImShow("Differences", image1);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
}
}
}
运行: