74 lines
2.3 KiB
C#
74 lines
2.3 KiB
C#
using OpenCvSharp;
|
|
|
|
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
|
|
{
|
|
/// <summary>
|
|
/// 图像相减 — func.Src 与局部图像做绝对差值。
|
|
/// 常用于缺陷检测、变化检测。
|
|
/// </summary>
|
|
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.FailMessage = "请先获取图片!"; return false;
|
|
}
|
|
|
|
if (!item.StringParams.TryGetValue("Image", out var imageName) || string.IsNullOrEmpty(imageName))
|
|
{
|
|
item.Flow.FailMessage = "请选择要相减的局部图像!";
|
|
return false;
|
|
}
|
|
|
|
var imageData = func.LocalImageDatas.FirstOrDefault(i => i.Name == imageName);
|
|
if (imageData?.Mat == null || imageData.Mat.Empty())
|
|
{
|
|
item.Flow.FailMessage = $"局部图像池中未找到图片:{imageName}";
|
|
return false;
|
|
}
|
|
|
|
using Mat other = imageData.Mat.Clone();
|
|
|
|
// 尺寸不一致时,取交集区域
|
|
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)];
|
|
|
|
// 统一为灰度做差值
|
|
Mat graySrc = new();
|
|
Mat grayOther = new();
|
|
if (srcRoi.Channels() == 1)
|
|
{
|
|
graySrc = srcRoi.Clone();
|
|
}
|
|
else
|
|
{
|
|
Cv2.CvtColor(srcRoi, graySrc, ColorConversionCodes.BGR2GRAY);
|
|
}
|
|
|
|
if (otherRoi.Channels() == 1)
|
|
{
|
|
grayOther = otherRoi.Clone();
|
|
}
|
|
else
|
|
{
|
|
Cv2.CvtColor(otherRoi, grayOther, ColorConversionCodes.BGR2GRAY);
|
|
}
|
|
|
|
// 绝对差值
|
|
Cv2.Absdiff(graySrc, grayOther, graySrc);
|
|
grayOther.Dispose();
|
|
|
|
// 写回 func.Src
|
|
func.Src.Dispose();
|
|
func.Src = graySrc;
|
|
return true;
|
|
}
|
|
}
|
|
}
|