改进一些显示
This commit is contained in:
parent
e54d1ec507
commit
7f8cc4ecd2
104
PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs
Normal file
104
PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs
Normal file
@ -0,0 +1,104 @@
|
||||
#nullable enable
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.GalleryClassifier
|
||||
{
|
||||
/// <summary>
|
||||
/// 特征提取器 —— 在原始分辨率下将 ROI 区域分成格子,提取统计特征。
|
||||
/// 不缩放、不依赖 ONNX 模型,细节不丢失。
|
||||
///
|
||||
/// 每个格子提取 2 个特征:灰度均值 + 灰度标准差
|
||||
/// 默认 8x8 格子 → 128 维特征向量
|
||||
/// </summary>
|
||||
public class FeatureExtractor : IDisposable
|
||||
{
|
||||
private readonly int _gridX;
|
||||
private readonly int _gridY;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>特征向量维度 = gridX × gridY × 2</summary>
|
||||
public int FeatureDimension => _gridX * _gridY * 2;
|
||||
|
||||
public FeatureExtractor(int gridX = 8, int gridY = 8)
|
||||
{
|
||||
_gridX = gridX > 0 ? gridX : throw new ArgumentException("gridX > 0");
|
||||
_gridY = gridY > 0 ? gridY : throw new ArgumentException("gridY > 0");
|
||||
}
|
||||
|
||||
public unsafe float[] Extract(Mat image)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (image == null || image.Empty())
|
||||
throw new ArgumentException("图像为空");
|
||||
|
||||
Mat gray;
|
||||
if (image.Channels() == 1)
|
||||
gray = image.Clone();
|
||||
else
|
||||
{
|
||||
gray = new Mat();
|
||||
Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
int cellW = Math.Max(gray.Width / _gridX, 1);
|
||||
int cellH = Math.Max(gray.Height / _gridY, 1);
|
||||
|
||||
float[] features = new float[_gridX * _gridY * 2];
|
||||
int idx = 0;
|
||||
|
||||
for (int gy = 0; gy < _gridY; gy++)
|
||||
{
|
||||
for (int gx = 0; gx < _gridX; gx++)
|
||||
{
|
||||
int x = gx * cellW;
|
||||
int y = gy * cellH;
|
||||
int w = (gx == _gridX - 1) ? gray.Width - x : cellW;
|
||||
int h = (gy == _gridY - 1) ? gray.Height - y : cellH;
|
||||
int pixelCount = w * h;
|
||||
if (pixelCount <= 0) { idx += 2; continue; }
|
||||
|
||||
float sum = 0f;
|
||||
float sumSq = 0f;
|
||||
|
||||
for (int row = y; row < y + h; row++)
|
||||
{
|
||||
byte* rowPtr = (byte*)gray.DataPointer + row * gray.Step();
|
||||
for (int col = x; col < x + w; col++)
|
||||
{
|
||||
byte v = rowPtr[col];
|
||||
sum += v;
|
||||
sumSq += v * v;
|
||||
}
|
||||
}
|
||||
|
||||
float mean = sum / pixelCount;
|
||||
float variance = (sumSq / pixelCount) - (mean * mean);
|
||||
|
||||
features[idx++] = mean / 255f;
|
||||
features[idx++] = MathF.Sqrt(MathF.Max(variance, 0f)) / 255f;
|
||||
}
|
||||
}
|
||||
|
||||
return features;
|
||||
}
|
||||
finally
|
||||
{
|
||||
gray?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException(nameof(FeatureExtractor));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,129 +0,0 @@
|
||||
#nullable enable
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Dnn;
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.GalleryClassifier
|
||||
{
|
||||
/// <summary>
|
||||
/// ONNX 特征提取器 —— 使用 OpenCvSharp DNN 模块,不依赖额外 NuGet 包。
|
||||
///
|
||||
/// 需要:一个输出 embedding 的 .onnx 模型文件
|
||||
/// 推荐:MobileNetV3-Large 去掉分类头后导出
|
||||
/// </summary>
|
||||
public class OnnxEmbedding : IDisposable
|
||||
{
|
||||
private readonly Net _net;
|
||||
private readonly int _inputWidth;
|
||||
private readonly int _inputHeight;
|
||||
private readonly int _featureDimension;
|
||||
private bool _disposed;
|
||||
|
||||
private static readonly float[] Mean = [0.485f, 0.456f, 0.406f];
|
||||
private static readonly float[] Std = [0.229f, 0.224f, 0.225f];
|
||||
|
||||
/// <summary>输出特征向量维度</summary>
|
||||
public int FeatureDimension => _featureDimension;
|
||||
|
||||
public OnnxEmbedding(string modelPath, int inputWidth = 224, int inputHeight = 224,
|
||||
int featureDimension = -1)
|
||||
{
|
||||
_net = Cv2.Dnn.ReadNetFromONNX(modelPath);
|
||||
_inputWidth = inputWidth;
|
||||
_inputHeight = inputHeight;
|
||||
|
||||
// 默认 CPU 推理
|
||||
|
||||
if (featureDimension > 0)
|
||||
{
|
||||
_featureDimension = featureDimension;
|
||||
}
|
||||
else
|
||||
{
|
||||
using var dummy = new Mat(_inputHeight, _inputWidth, MatType.CV_8UC3, Scalar.All(0));
|
||||
using var blob = BlobFromImage(dummy);
|
||||
_net.SetInput(blob);
|
||||
using var output = _net.Forward();
|
||||
_featureDimension = (int)output.Total();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 BGR 图像提取 L2 归一化的特征向量
|
||||
/// </summary>
|
||||
public float[] Extract(Mat image)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (image == null || image.Empty())
|
||||
throw new ArgumentException("图像为空");
|
||||
|
||||
using var blob = BlobFromImage(image);
|
||||
_net.SetInput(blob);
|
||||
using var output = _net.Forward();
|
||||
|
||||
int total = (int)output.Total();
|
||||
float[] feature = new float[total];
|
||||
Marshal.Copy(output.DataStart, feature, 0, total);
|
||||
|
||||
return L2Normalize(feature);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 图像预处理:resize → BGR→RGB → [0,1] → (x - mean) / std
|
||||
/// OpenCV blobFromImage 不支持除 std,所以先做 resize+swapRB,再手动归一化
|
||||
/// </summary>
|
||||
private Mat BlobFromImage(Mat image)
|
||||
{
|
||||
int w = _inputWidth, h = _inputHeight;
|
||||
|
||||
// resize + BGR→RGB,不做归一化
|
||||
var blob = Cv2.Dnn.BlobFromImage(image, 1.0, new Size(w, h),
|
||||
new Scalar(0, 0, 0), swapRB: true, crop: false);
|
||||
|
||||
int total = (int)blob.Total(); // 3 * H * W
|
||||
float[] data = new float[total];
|
||||
Marshal.Copy(blob.DataStart, data, 0, total);
|
||||
|
||||
// NCHW: data[c, h, w] = (pixel - mean[c] * 255) / (std[c] * 255)
|
||||
// 由于 blobFromImage(scale=1.0) 时 pixel 还是 [0,255] 原始值
|
||||
int hw = h * w;
|
||||
for (int i = 0; i < total; i++)
|
||||
{
|
||||
int c = i / hw;
|
||||
data[i] = (data[i] / 255f - Mean[c]) / Std[c];
|
||||
}
|
||||
|
||||
Marshal.Copy(data, 0, blob.DataStart, total);
|
||||
return blob;
|
||||
}
|
||||
|
||||
private static float[] L2Normalize(float[] vector)
|
||||
{
|
||||
float sumSq = 0f;
|
||||
foreach (var v in vector) sumSq += v * v;
|
||||
float norm = MathF.Sqrt(sumSq);
|
||||
if (norm < 1e-10f) return vector;
|
||||
|
||||
var result = new float[vector.Length];
|
||||
for (int i = 0; i < vector.Length; i++)
|
||||
result[i] = vector[i] / norm;
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
_net?.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException(nameof(OnnxEmbedding));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -22,36 +22,6 @@ namespace PLCSharp.VVMs.Vision
|
||||
private float[]? _lastGalleryFeature;
|
||||
private bool _lastGalleryWasOk;
|
||||
|
||||
#region 模型路径
|
||||
|
||||
private DelegateCommand _BrowseGalleryModelCommand;
|
||||
public DelegateCommand BrowseGalleryModelCommand =>
|
||||
_BrowseGalleryModelCommand ??= new DelegateCommand(ExecuteBrowseGalleryModel);
|
||||
private void ExecuteBrowseGalleryModel()
|
||||
{
|
||||
var dialog = new Microsoft.Win32.OpenFileDialog
|
||||
{
|
||||
Filter = "ONNX 模型|*.onnx",
|
||||
Title = "选择特征提取模型"
|
||||
};
|
||||
if (dialog.ShowDialog() != true) return;
|
||||
if (SelectVisionFlow == null) return;
|
||||
|
||||
SelectVisionFlow.StringParams["GalleryModelPath"] = dialog.FileName;
|
||||
|
||||
var embedding = GalleryClassifierHandler.GetOrCreateEmbedding(dialog.FileName);
|
||||
GalleryModelStatus = embedding != null ? "模型已加载" : "模型加载失败";
|
||||
}
|
||||
|
||||
private string _GalleryModelStatus = "请选择 ONNX 模型文件";
|
||||
public string GalleryModelStatus
|
||||
{
|
||||
get => _GalleryModelStatus;
|
||||
set => SetProperty(ref _GalleryModelStatus, value);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ROI 选区
|
||||
|
||||
private AsyncDelegateCommand _DrawGalleryRoiCommand;
|
||||
@ -152,16 +122,13 @@ namespace PLCSharp.VVMs.Vision
|
||||
private bool CanTrainGallery()
|
||||
{
|
||||
return SelectedVisionFunction?.Src != null && !SelectedVisionFunction.Src.Empty()
|
||||
&& SelectVisionFlow != null
|
||||
&& GalleryClassifierHandler.SharedEmbedding != null;
|
||||
&& SelectVisionFlow != null;
|
||||
}
|
||||
|
||||
private FeatureGallery GetGallery()
|
||||
{
|
||||
var flow = SelectVisionFlow ?? throw new InvalidOperationException("未选择步骤");
|
||||
var dim = GalleryClassifierHandler.SharedEmbedding?.FeatureDimension
|
||||
?? throw new InvalidOperationException("模型未加载");
|
||||
return GalleryClassifierHandler.LoadFromData(flow, dim);
|
||||
return GalleryClassifierHandler.LoadFromData(flow, GalleryClassifierHandler.FeatureDimension);
|
||||
}
|
||||
|
||||
private void SaveGallery(FeatureGallery gallery)
|
||||
@ -255,13 +222,18 @@ namespace PLCSharp.VVMs.Vision
|
||||
};
|
||||
if (dialog.ShowDialog() != true) return;
|
||||
if (SelectVisionFlow == null) return;
|
||||
if (GalleryClassifierHandler.SharedEmbedding == null) return;
|
||||
|
||||
var json = File.ReadAllText(dialog.FileName);
|
||||
var data = System.Text.Json.JsonSerializer.Deserialize<GalleryData>(json);
|
||||
if (data == null) return;
|
||||
|
||||
var gallery = new FeatureGallery(GalleryClassifierHandler.SharedEmbedding.FeatureDimension);
|
||||
if (data.Dimension != GalleryClassifierHandler.FeatureDimension)
|
||||
{
|
||||
GalleryFileStatus = $"导入失败:特征维度不匹配(文件 {data.Dimension},当前 {GalleryClassifierHandler.FeatureDimension})";
|
||||
return;
|
||||
}
|
||||
|
||||
var gallery = new FeatureGallery(GalleryClassifierHandler.FeatureDimension);
|
||||
gallery.Import(data);
|
||||
GalleryClassifierHandler.SaveToData(SelectVisionFlow, gallery);
|
||||
|
||||
@ -278,10 +250,8 @@ namespace PLCSharp.VVMs.Vision
|
||||
GalleryStatus = "没有图像";
|
||||
return null;
|
||||
}
|
||||
var embedding = GalleryClassifierHandler.SharedEmbedding;
|
||||
if (embedding == null) return null;
|
||||
|
||||
// ROI 裁剪(与 Handler 中一致):裁剪后提取特征,不影响原图
|
||||
// ROI 裁剪(与 Handler 中一致)
|
||||
var flow = SelectVisionFlow;
|
||||
Mat? roiCloned = null;
|
||||
try
|
||||
@ -300,7 +270,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
if (w > 0 && h > 0)
|
||||
roiCloned = src[new OpenCvSharp.Rect(x, y, w, h)].Clone();
|
||||
}
|
||||
return embedding.Extract(roiCloned ?? func.Src);
|
||||
return GalleryClassifierHandler.Extractor.Extract(roiCloned ?? func.Src);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@ -318,11 +288,10 @@ namespace PLCSharp.VVMs.Vision
|
||||
private void RefreshGalleryResult(FeatureGallery gallery)
|
||||
{
|
||||
var func = SelectedVisionFunction;
|
||||
if (func?.Src == null || func.Src.Empty()
|
||||
|| GalleryClassifierHandler.SharedEmbedding == null)
|
||||
if (func?.Src == null || func.Src.Empty())
|
||||
return;
|
||||
|
||||
var feature = GalleryClassifierHandler.SharedEmbedding.Extract(func.Src);
|
||||
var feature = GalleryClassifierHandler.Extractor.Extract(func.Src);
|
||||
var result = gallery.Classify(feature);
|
||||
|
||||
func.ResultString = result.IsOk ? "OK" : "NG";
|
||||
|
||||
@ -88,7 +88,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
|
||||
// 将轮廓点偏移回原图坐标系
|
||||
var offsetPts = largest.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray();
|
||||
func.DrawCommands.Add(DrawCommand.Polygon(offsetPts, Colors.Yellow, 2));
|
||||
func.DrawCommands.Add(DrawCommand.FilledPolygon(offsetPts, Colors.Yellow, Colors.Yellow, 2));
|
||||
|
||||
// 如果有多个较大轮廓,也画出来(面积大于最大轮廓20%的)
|
||||
double maxArea = Cv2.ContourArea(largest);
|
||||
@ -97,14 +97,14 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
if (Cv2.ContourArea(contour) >= maxArea * 0.2)
|
||||
{
|
||||
var pts = contour.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray();
|
||||
func.DrawCommands.Add(DrawCommand.Polygon(pts, Colors.Yellow, 1));
|
||||
func.DrawCommands.Add(DrawCommand.FilledPolygon(pts, Colors.Yellow, Colors.Yellow, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 在图像上显示结果文本
|
||||
string text = $"颜色面积: {areaPercent:F1}% [{result}]";
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 14));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 48));
|
||||
|
||||
// 写入结果到ResultDoubles
|
||||
func.Params.ResultDoubles["ColorAreaPercent"] = Math.Round(areaPercent, 2);
|
||||
|
||||
@ -9,31 +9,7 @@
|
||||
d:DesignHeight="500" d:DesignWidth="300">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel>
|
||||
<!-- ========== 模型配置 ========== -->
|
||||
<GroupBox Header="模型">
|
||||
<StackPanel>
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Text="{Binding SelectVisionFlow.StringParams[GalleryModelPath], Mode=TwoWay}"
|
||||
ToolTip=".onnx 模型文件路径" />
|
||||
<Button Grid.Column="1" Content="浏览"
|
||||
Command="{Binding BrowseGalleryModelCommand}"
|
||||
Height="22" Width="50" Margin="3,0,0,0"/>
|
||||
<TextBlock Grid.Row="1" Grid.ColumnSpan="2"
|
||||
Text="{Binding GalleryModelStatus, Mode=OneWay}"
|
||||
FontSize="12" Margin="0,3,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- ========== ROI 区域 ========== -->
|
||||
<!-- ========== ROI 区域(选区用于分类,不影响原图) ========== -->
|
||||
<GroupBox Header="ROI 区域(选区用于分类,不影响原图)">
|
||||
<StackPanel>
|
||||
<Button Height="25" Margin="5" Command="{Binding DrawGalleryRoiCommand}" Content="画选区" />
|
||||
@ -67,7 +43,6 @@
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
@ -85,12 +60,6 @@
|
||||
<Button Grid.Row="1" Grid.Column="1" Content="纠正为 NG"
|
||||
Command="{Binding CorrectGalleryToNgCommand}"
|
||||
Height="28" Margin="3,0,0,3" FontSize="11"/>
|
||||
<Button Grid.Row="2" Grid.Column="0" Content="撤销"
|
||||
Command="{Binding UndoGalleryCommand}"
|
||||
Height="28" Margin="0,0,3,0"/>
|
||||
<Button Grid.Row="2" Grid.Column="1" Content="清空"
|
||||
Command="{Binding ClearGalleryCommand}"
|
||||
Height="28" Margin="3,0,0,0"/>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
@ -135,24 +104,19 @@
|
||||
<ColumnDefinition />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Grid.ColumnSpan="2" Text="— 最近一次推理 —" FontWeight="Bold" HorizontalAlignment="Center" />
|
||||
|
||||
<TextBlock Grid.Row="1" Margin="5,0" Text="结果" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.ResultString, Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="2" Margin="5,0" Text="OK 距离" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Gallery_OKDist], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="3" Margin="5,0" Text="NG 距离" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="3" Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Gallery_NGDist], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="4" Margin="5,0" Text="置信度" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="4" Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Gallery_Confidence], Mode=OneWay}"
|
||||
@ -160,7 +124,7 @@
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<!-- ========== 保存/加载 ========== -->
|
||||
<!-- ========== 文件 ========== -->
|
||||
<GroupBox Header="文件">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
|
||||
@ -1,37 +1,26 @@
|
||||
#nullable enable
|
||||
#nullable enable
|
||||
using OpenCvSharp;
|
||||
using PLCSharp.VVMs.Vision.GalleryClassifier;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// 画廊分类 Handler。
|
||||
/// 支持 ROI 选区:只对选区提取特征做分类,不影响原图,结果在原图上绘制。
|
||||
/// 画廊分类 Handler —— 本地特征提取(不依赖 ONNX 模型)。
|
||||
/// 画廊数据存在 VisionFlow.GalleryData 中,随流程步骤自动序列化。
|
||||
/// 先执行 ROI 剪切步骤再做分类。
|
||||
/// </summary>
|
||||
public class GalleryClassifierHandler : IVisionFlowHandler
|
||||
{
|
||||
private static OnnxEmbedding? _sharedEmbedding;
|
||||
private static string? _loadedModelPath;
|
||||
private static FeatureExtractor? _extractor;
|
||||
|
||||
public VisionFlowType Type => VisionFlowType.画廊分类;
|
||||
|
||||
public static OnnxEmbedding? GetOrCreateEmbedding(string modelPath)
|
||||
{
|
||||
if (_sharedEmbedding != null && _loadedModelPath == modelPath)
|
||||
return _sharedEmbedding;
|
||||
if (!File.Exists(modelPath))
|
||||
return null;
|
||||
_sharedEmbedding?.Dispose();
|
||||
_sharedEmbedding = new OnnxEmbedding(modelPath, 224, 224, 960);
|
||||
_loadedModelPath = modelPath;
|
||||
return _sharedEmbedding;
|
||||
}
|
||||
public static FeatureExtractor Extractor =>
|
||||
_extractor ??= new FeatureExtractor(8, 8);
|
||||
|
||||
public static OnnxEmbedding? SharedEmbedding => _sharedEmbedding;
|
||||
public static int FeatureDimension => Extractor.FeatureDimension;
|
||||
|
||||
public bool Execute(VisionFunction func, VisionFlow item)
|
||||
{
|
||||
@ -39,18 +28,9 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
if (src == null || src.Empty())
|
||||
throw new Exception("请先获取图片!");
|
||||
|
||||
string? modelPath = item.StringParams.TryGetValue("GalleryModelPath", out var mp)
|
||||
&& !string.IsNullOrEmpty(mp) ? mp : null;
|
||||
if (string.IsNullOrEmpty(modelPath) || !File.Exists(modelPath))
|
||||
throw new Exception("请先在步骤参数中点击 [浏览] 选择 .onnx 模型文件");
|
||||
var gallery = LoadFromData(item, FeatureDimension);
|
||||
|
||||
var embedding = GetOrCreateEmbedding(modelPath);
|
||||
if (embedding == null)
|
||||
throw new Exception("模型加载失败");
|
||||
|
||||
var gallery = LoadFromData(item, embedding.FeatureDimension);
|
||||
|
||||
// ROI 裁剪:从原图裁出选区用于分类,不影响 func.Src
|
||||
// ROI 裁剪(可选):只对选区提取特征,不影响 func.Src
|
||||
Mat? roiCloned = null;
|
||||
Mat extractSrc = src;
|
||||
try
|
||||
@ -71,7 +51,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
}
|
||||
}
|
||||
|
||||
float[] feature = embedding.Extract(extractSrc);
|
||||
float[] feature = Extractor.Extract(extractSrc);
|
||||
var result = gallery.Classify(feature);
|
||||
|
||||
func.ResultString = result.IsOk ? "OK" : "NG";
|
||||
@ -81,17 +61,15 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.Params.ResultDoubles["Gallery_Delta"] = Math.Round(result.Delta, 6);
|
||||
func.Params.ResultDoubles["Gallery_Confidence"] = Math.Round(result.OkConfidence, 4);
|
||||
|
||||
// 在原图上绘制 ROI 框 + 分类结果
|
||||
var color = result.IsOk ? Colors.Lime : Colors.Red;
|
||||
|
||||
// 如果有 ROI,画矩形框并标注结果
|
||||
// 在原图上画 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)
|
||||
@ -102,9 +80,8 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
}
|
||||
else
|
||||
{
|
||||
// 全图分类,在左上角显示
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(10, 100,
|
||||
$"画廊分类: {func.ResultString}", color, 64));
|
||||
$"画廊分类: {func.ResultString}", color, 48));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(10, 200,
|
||||
$"OK距离: {result.OkDistance:F6} NG距离: {result.NgDistance:F6}", color, 48));
|
||||
}
|
||||
@ -123,7 +100,17 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
var gallery = new FeatureGallery(dimension);
|
||||
if (item.GalleryData != null)
|
||||
gallery.Import(item.GalleryData);
|
||||
{
|
||||
try
|
||||
{
|
||||
gallery.Import(item.GalleryData);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// 维度不匹配(如旧版 ONNX 960 维 → 当前 128 维),忽略旧数据
|
||||
gallery = new FeatureGallery(dimension);
|
||||
}
|
||||
}
|
||||
return gallery;
|
||||
}
|
||||
|
||||
|
||||
@ -82,7 +82,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
var largest = sorted[0];
|
||||
|
||||
var offsetPts = largest.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray();
|
||||
func.DrawCommands.Add(DrawCommand.Polygon(offsetPts, Colors.Yellow, 2));
|
||||
func.DrawCommands.Add(DrawCommand.FilledPolygon(offsetPts, Colors.Yellow, Colors.Yellow, 2));
|
||||
|
||||
double maxArea = Cv2.ContourArea(largest);
|
||||
foreach (var contour in sorted.Skip(1))
|
||||
@ -90,14 +90,14 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
if (Cv2.ContourArea(contour) >= maxArea * 0.2)
|
||||
{
|
||||
var pts = contour.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray();
|
||||
func.DrawCommands.Add(DrawCommand.Polygon(pts, Colors.Yellow, 1));
|
||||
func.DrawCommands.Add(DrawCommand.FilledPolygon(pts, Colors.Yellow, Colors.Yellow, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 在图像上显示结果文本
|
||||
string text = $"灰度面积: {areaPercent:F1}% [{result}]";
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 14));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 48));
|
||||
|
||||
// 写入结果到ResultDoubles
|
||||
func.Params.ResultDoubles["GrayAreaPercent"] = Math.Round(areaPercent, 2);
|
||||
|
||||
@ -270,11 +270,11 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.DrawCommands.Add(DrawCommand.Line(matchX - 15, matchY, matchX + 15, matchY, magenta, 2));
|
||||
func.DrawCommands.Add(DrawCommand.Line(matchX, matchY - 15, matchX, matchY + 15, magenta, 2));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(10, 100,
|
||||
$"x:{matchX:F1} y:{matchY:F1} a:{bestAngle:F1}° s:{bestScore:F4}", lime, 64));
|
||||
$"x:{matchX:F1} y:{matchY:F1} a:{bestAngle:F1}° s:{bestScore:F4}", lime, 48));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(10, 200,
|
||||
$"offset: ({offsetX:+0.0;-0.0}, {offsetY:+0.0;-0.0})", lime, 64));
|
||||
$"offset: ({offsetX:+0.0;-0.0}, {offsetY:+0.0;-0.0})", lime, 48));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(10, 300,
|
||||
$"[灰度模板匹配] {totalTemplates} templates", lime, 64));
|
||||
$"[灰度模板匹配] {totalTemplates} templates", lime, 48));
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
|
||||
@ -134,7 +134,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.DrawCommands.Add(DrawCommand.FilledCircle(footX, footY, 3, Colors.Cyan));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(
|
||||
(point.X + footX) / 2, (point.Y + footY) / 2 - 10,
|
||||
$"{func.Params.ResultDoubles["PointLineDist_Distance"]:F3}", Colors.Lime, 16));
|
||||
$"{func.Params.ResultDoubles["PointLineDist_Distance"]:F3}", Colors.Lime, 48));
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
return true;
|
||||
|
||||
@ -94,7 +94,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
func.DrawCommands.Add(DrawCommand.FilledCircle(pos2.X, pos2.Y, 4, Colors.Cyan));
|
||||
func.DrawCommands.Add(DrawCommand.TextBlock(
|
||||
(pos1.X + pos2.X) / 2 + 5, (pos1.Y + pos2.Y) / 2 - 5,
|
||||
$"{func.Params.ResultDoubles["PointDist_Distance"]:F3}", Colors.Lime, 16));
|
||||
$"{func.Params.ResultDoubles["PointDist_Distance"]:F3}", Colors.Lime, 48));
|
||||
_ = func.RenderDrawAsync();
|
||||
item.Flow.Done = true;
|
||||
return true;
|
||||
|
||||
@ -16,6 +16,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler
|
||||
public double Thickness { get; init; } = 1;
|
||||
public bool Filled { get; init; }
|
||||
public Color Color { get; init; } = Colors.Magenta;
|
||||
public Color? FillColor { get; init; }
|
||||
public Point[] Points { get; init; }
|
||||
public string Text { get; init; }
|
||||
public double FontSize { get; init; } = 12;
|
||||
@ -38,5 +39,8 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler
|
||||
|
||||
public static DrawCommand Polygon(System.Windows.Point[] pts, Color color, double thickness = 1)
|
||||
=> new() { Shape = Type.Polygon, Points = pts.Select(p => new Point(p.X, p.Y)).ToArray(), Color = color, Thickness = thickness };
|
||||
|
||||
public static DrawCommand FilledPolygon(System.Windows.Point[] pts, Color strokeColor, Color fillColor, double thickness = 1)
|
||||
=> new() { Shape = Type.Polygon, Points = pts.Select(p => new Point(p.X, p.Y)).ToArray(), Color = strokeColor, FillColor = fillColor, Thickness = thickness };
|
||||
}
|
||||
}
|
||||
|
||||
@ -483,7 +483,9 @@ namespace PLCSharp.VVMs.Vision
|
||||
cmd.Points.Select(p => new System.Windows.Point(p.X, p.Y))),
|
||||
Stroke = new SolidColorBrush(cmd.Color),
|
||||
StrokeThickness = cmd.Thickness,
|
||||
Fill = Brushes.Transparent,
|
||||
Fill = cmd.FillColor.HasValue
|
||||
? new SolidColorBrush(Color.FromArgb(80, cmd.FillColor.Value.R, cmd.FillColor.Value.G, cmd.FillColor.Value.B))
|
||||
: Brushes.Transparent,
|
||||
Tag = "DrawOverlay"
|
||||
};
|
||||
EditImageEdit.Draw(poly);
|
||||
@ -550,7 +552,9 @@ namespace PLCSharp.VVMs.Vision
|
||||
cmd.Points.Select(p => new System.Windows.Point(p.X, p.Y))),
|
||||
Stroke = new SolidColorBrush(cmd.Color),
|
||||
StrokeThickness = cmd.Thickness,
|
||||
Fill = Brushes.Transparent,
|
||||
Fill = cmd.FillColor.HasValue
|
||||
? new SolidColorBrush(Color.FromArgb(80, cmd.FillColor.Value.R, cmd.FillColor.Value.G, cmd.FillColor.Value.B))
|
||||
: Brushes.Transparent,
|
||||
Tag = "DrawOverlay"
|
||||
};
|
||||
imageEdit.Draw(poly);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user