plcsharp/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifierHandler.cs

122 lines
5.0 KiB
C#

#nullable enable
using OpenCvSharp;
using PLCSharp.VVMs.Vision.GalleryClassifier;
using System.Windows.Media;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 画廊分类 Handler —— 本地特征提取(不依赖 ONNX 模型)。
/// 画廊数据存在 VisionFlow.GalleryData 中,随流程步骤自动序列化。
/// 先执行 ROI 剪切步骤再做分类。
/// </summary>
public class GalleryClassifierHandler : IVisionFlowHandler
{
private static FeatureExtractor? _extractor;
public VisionFlowType Type => VisionFlowType.画廊分类;
public static FeatureExtractor Extractor =>
_extractor ??= new FeatureExtractor(8, 8);
public static int FeatureDimension => Extractor.FeatureDimension;
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src;
if (src == null || src.Empty())
throw new Exception("请先获取图片!");
var gallery = LoadFromData(item, FeatureDimension);
// ROI 裁剪(可选):只对选区提取特征,不影响 func.Src
Mat? roiCloned = null;
Mat extractSrc = src;
try
{
if (item.DoubleParams.TryGetValue("GalleryRoiLeft", out double rl) &&
item.DoubleParams.TryGetValue("GalleryRoiTop", out double rt) &&
item.DoubleParams.TryGetValue("GalleryRoiWidth", out double rw) &&
item.DoubleParams.TryGetValue("GalleryRoiHeight", out double rh))
{
int x = Math.Clamp((int)rl, 0, src.Width - 1);
int y = Math.Clamp((int)rt, 0, src.Height - 1);
int w = Math.Min((int)rw, src.Width - x);
int h = Math.Min((int)rh, src.Height - y);
if (w > 0 && h > 0)
{
roiCloned = src[new OpenCvSharp.Rect(x, y, w, h)].Clone();
extractSrc = roiCloned;
}
}
float[] feature = Extractor.Extract(extractSrc);
var result = gallery.Classify(feature);
func.ResultString = result.IsOk ? "OK" : "NG";
func.ResultDouble = result.IsOk ? 1 : 0;
func.Params.ResultDoubles["Gallery_OKDist"] = Math.Round(result.OkDistance, 6);
func.Params.ResultDoubles["Gallery_NGDist"] = Math.Round(result.NgDistance, 6);
func.Params.ResultDoubles["Gallery_Delta"] = Math.Round(result.Delta, 6);
func.Params.ResultDoubles["Gallery_Confidence"] = Math.Round(result.OkConfidence, 4);
var color = result.IsOk ? Colors.Lime : Colors.Red;
// 在原图上画 ROI 框 + 分类结果
if (roiCloned != null)
{
double rrx = item.DoubleParams["GalleryRoiLeft"];
double rry = item.DoubleParams["GalleryRoiTop"];
double rrw = item.DoubleParams["GalleryRoiWidth"];
double rrh = item.DoubleParams["GalleryRoiHeight"];
func.DrawCommands.Add(DrawCommand.Polygon([
new(rrx, rry), new(rrx + rrw, rry),
new(rrx + rrw, rry + rrh), new(rrx, rry + rrh)
], color, 3));
func.DrawCommands.Add(DrawCommand.TextBlock(rrx, rry - 30,
$"画廊分类: {func.ResultString} (OK:{result.OkDistance:F4} NG:{result.NgDistance:F4})",
color, 48));
}
else
{
func.DrawCommands.Add(DrawCommand.TextBlock(10, 100,
$"画廊分类: {func.ResultString}", color, 48));
func.DrawCommands.Add(DrawCommand.TextBlock(10, 200,
$"OK距离: {result.OkDistance:F6} NG距离: {result.NgDistance:F6}", color, 48));
}
_ = func.RenderDrawAsync();
item.Flow.Done = true;
return true;
}
finally
{
roiCloned?.Dispose();
}
}
public static FeatureGallery LoadFromData(VisionFlow item, int dimension)
{
var gallery = new FeatureGallery(dimension);
if (item.GalleryData != null)
{
try
{
gallery.Import(item.GalleryData);
}
catch (ArgumentException)
{
// 维度不匹配(如旧版 ONNX 960 维 → 当前 128 维),忽略旧数据
gallery = new FeatureGallery(dimension);
}
}
return gallery;
}
public static void SaveToData(VisionFlow item, FeatureGallery gallery)
{
item.GalleryData = gallery.Export();
}
}
}