using OpenCvSharp; namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing { /// /// 图像相减 — func.Src 与全局图像做绝对差值。 /// 常用于缺陷检测、变化检测。 /// public class ImageSubtractHandler : IVisionFlowHandler { public VisionFlowType Type => VisionFlowType.图像相减; public bool Execute(VisionFunction func, VisionFlow item) { var src = func.Src; if (src == null || src.Empty()) { item.Flow.ErrorState = "请先获取图片!"; return false; } if (!item.StringParams.TryGetValue("Image", out var imageName) || string.IsNullOrEmpty(imageName)) { item.Flow.ErrorState = "请选择要相减的全局图像!"; return false; } var imageData = func.ImageDatas.FirstOrDefault(i => i.Name == imageName); if (imageData?.Mat == null || imageData.Mat.Empty()) { item.Flow.ErrorState = $"全局图像池中未找到图片:{imageName}"; return false; } using Mat other = imageData.Mat; // 尺寸不一致时,取交集区域 int w = Math.Min(src.Width, other.Width); int h = Math.Min(src.Height, other.Height); using Mat srcRoi = src[new OpenCvSharp.Rect(0, 0, w, h)]; using Mat otherRoi = other[new OpenCvSharp.Rect(0, 0, w, h)]; // 统一为灰度做差值 using Mat graySrc = new(); using Mat grayOther = new(); Cv2.CvtColor(srcRoi, graySrc, ColorConversionCodes.BGR2GRAY); Cv2.CvtColor(otherRoi, grayOther, ColorConversionCodes.BGR2GRAY); // 绝对差值 Cv2.Absdiff(graySrc, grayOther, graySrc); // 写回 func.Src(BGR 格式) var oldSrc = func.Src; func.Src = new Mat(); Cv2.CvtColor(graySrc, func.Src, ColorConversionCodes.GRAY2BGR); oldSrc.Dispose(); item.Flow.Done = true; return true; } } }