plcsharp/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs

329 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#nullable enable
using OpenCvSharp;
using PLCSharp.Core.UserControls;
using PLCSharp.VVMs.Vision.GalleryClassifier;
using PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm;
using Prism.Commands;
using System.IO;
using System.Windows.Input;
namespace PLCSharp.VVMs.Vision
{
/// <summary>
/// 视觉流程配置界面 —— 画廊分类的训练命令
/// </summary>
public partial class VisionConfigViewModel
{
#region 画廊分类
// 撤销状态(只记上一步,跟 SelectVisionFlow 绑定)
private string? _lastGalleryAction;
private float[]? _lastGalleryFeature;
private bool _lastGalleryWasOk;
#region ROI 选区
private AsyncDelegateCommand _DrawGalleryRoiCommand;
public AsyncDelegateCommand DrawGalleryRoiCommand =>
_DrawGalleryRoiCommand ??= new AsyncDelegateCommand(ExecuteDrawGalleryRoiAsync);
private async System.Threading.Tasks.Task ExecuteDrawGalleryRoiAsync()
{
var imageEdit = SelectedVisionFunction?.EditImageEdit;
if (imageEdit?.ImageSource == null)
{
SendInfoDialog("请先获取图片!");
return;
}
if (SelectVisionFlow == null) return;
var roi = await imageEdit.DrawROIAsync("画廊分类ROI");
if (roi == null) return;
SelectVisionFlow.DoubleParams["GalleryRoiLeft"] = roi.Left;
SelectVisionFlow.DoubleParams["GalleryRoiTop"] = roi.Top;
SelectVisionFlow.DoubleParams["GalleryRoiWidth"] = roi.Width;
SelectVisionFlow.DoubleParams["GalleryRoiHeight"] = roi.Height;
imageEdit.DrawRectVisual(roi.Left, roi.Top, roi.Width, roi.Height);
SendInfoDialog("ROI 已保存");
}
#endregion ROI 选区
#region 训练命令
public ICommand TrainGalleryOkCommand => _TrainGalleryOk ??= new DelegateCommand(
() => TrainGallery(true), CanTrainGallery);
private DelegateCommand? _TrainGalleryOk;
public ICommand TrainGalleryNgCommand => _TrainGalleryNg ??= new DelegateCommand(
() => TrainGallery(false), CanTrainGallery);
private DelegateCommand? _TrainGalleryNg;
public ICommand CorrectGalleryToOkCommand => _CorrectGalleryToOk ??= new DelegateCommand(
() => CorrectGallery(true), CanTrainGallery);
private DelegateCommand? _CorrectGalleryToOk;
public ICommand CorrectGalleryToNgCommand => _CorrectGalleryToNg ??= new DelegateCommand(
() => CorrectGallery(false), CanTrainGallery);
private DelegateCommand? _CorrectGalleryToNg;
public ICommand UndoGalleryCommand => _UndoGallery ??= new DelegateCommand(
ExecuteUndoGallery, () => _lastGalleryAction != null);
private DelegateCommand? _UndoGallery;
public ICommand ClearGalleryCommand => _ClearGallery ??= new DelegateCommand(ExecuteClearGallery);
private DelegateCommand? _ClearGallery;
public ICommand ExportGalleryCommand => _ExportGallery ??= new DelegateCommand(ExecuteExportGallery);
private DelegateCommand? _ExportGallery;
public ICommand ImportGalleryCommand => _ImportGallery ??= new DelegateCommand(ExecuteImportGallery);
private DelegateCommand? _ImportGallery;
#endregion 训练命令
#region 绑定属性
private int _GalleryOkCount;
public int GalleryOkCount
{
get => _GalleryOkCount;
set => SetProperty(ref _GalleryOkCount, value);
}
private int _GalleryNgCount;
public int GalleryNgCount
{
get => _GalleryNgCount;
set => SetProperty(ref _GalleryNgCount, value);
}
private string _GalleryStatus = "等待操作...";
public string GalleryStatus
{
get => _GalleryStatus;
set => SetProperty(ref _GalleryStatus, value);
}
private string _GalleryFileStatus = "";
public string GalleryFileStatus
{
get => _GalleryFileStatus;
set => SetProperty(ref _GalleryFileStatus, value);
}
#endregion 绑定属性
#region 内部
private bool CanTrainGallery()
{
return SelectedVisionFunction?.Src != null && !SelectedVisionFunction.Src.Empty()
&& SelectVisionFlow != null;
}
private FeatureGallery GetGallery()
{
var flow = SelectVisionFlow ?? throw new InvalidOperationException("未选择步骤");
return GalleryClassifierHandler.LoadFromData(flow, GalleryClassifierHandler.FeatureDimension);
}
private void SaveGallery(FeatureGallery gallery)
{
var flow = SelectVisionFlow;
if (flow == null) return;
GalleryClassifierHandler.SaveToData(flow, gallery);
}
private void TrainGallery(bool isOk)
{
var feature = ExtractGalleryFeature();
if (feature == null) return;
var gallery = GetGallery();
if (isOk) gallery.AddOk(feature);
else gallery.AddNg(feature);
SaveGallery(gallery);
_lastGalleryAction = "train";
_lastGalleryFeature = feature;
_lastGalleryWasOk = isOk;
AfterGalleryTrain(isOk ? "训练为 OK" : "训练为 NG", gallery);
}
private void CorrectGallery(bool toOk)
{
var feature = ExtractGalleryFeature();
if (feature == null) return;
var gallery = GetGallery();
gallery.RemoveNearest(feature, fromOk: !toOk);
if (toOk) gallery.AddOk(feature);
else gallery.AddNg(feature);
SaveGallery(gallery);
_lastGalleryAction = "correct";
_lastGalleryFeature = feature;
_lastGalleryWasOk = toOk;
AfterGalleryTrain(toOk ? "纠正为 OK" : "纠正为 NG", gallery);
}
private void ExecuteUndoGallery()
{
if (_lastGalleryAction == null || _lastGalleryFeature == null) return;
var gallery = GetGallery();
gallery.RemoveNearest(_lastGalleryFeature, _lastGalleryWasOk);
SaveGallery(gallery);
_lastGalleryAction = null;
_lastGalleryFeature = null;
RefreshGalleryResult(gallery);
UpdateGalleryProperties(gallery);
GalleryStatus = "已撤销";
}
private void ExecuteClearGallery()
{
var gallery = GetGallery();
gallery.Clear();
SaveGallery(gallery);
_lastGalleryAction = null;
_lastGalleryFeature = null;
UpdateGalleryProperties(gallery);
GalleryStatus = "已清空";
}
private void ExecuteExportGallery()
{
var dialog = new Microsoft.Win32.SaveFileDialog
{
Filter = "画廊数据|*.json",
FileName = "gallery.json"
};
if (dialog.ShowDialog() != true) return;
var gallery = GetGallery();
var json = System.Text.Json.JsonSerializer.Serialize(gallery.Export());
File.WriteAllText(dialog.FileName, json);
GalleryFileStatus = "已导出";
}
private void ExecuteImportGallery()
{
var dialog = new Microsoft.Win32.OpenFileDialog
{
Filter = "画廊数据|*.json"
};
if (dialog.ShowDialog() != true) return;
if (SelectVisionFlow == null) return;
var json = File.ReadAllText(dialog.FileName);
var data = System.Text.Json.JsonSerializer.Deserialize<GalleryData>(json);
if (data == null) return;
if (data.Dimension != GalleryClassifierHandler.FeatureDimension)
{
GalleryFileStatus = $"导入失败:特征维度不匹配(文件 {data.Dimension},当前 {GalleryClassifierHandler.FeatureDimension})";
return;
}
var gallery = new FeatureGallery(GalleryClassifierHandler.FeatureDimension);
gallery.Import(data);
GalleryClassifierHandler.SaveToData(SelectVisionFlow, gallery);
UpdateGalleryProperties(gallery);
RefreshGalleryResult(gallery);
GalleryFileStatus = "已导入";
}
private float[]? ExtractGalleryFeature()
{
var func = SelectedVisionFunction;
if (func?.Src == null || func.Src.Empty())
{
GalleryStatus = "没有图像";
return null;
}
// ROI 裁剪(与 Handler 中一致)
var flow = SelectVisionFlow;
Mat? roiCloned = null;
try
{
Mat src = func.Src;
if (flow != null &&
flow.DoubleParams.TryGetValue("GalleryRoiLeft", out double rl) &&
flow.DoubleParams.TryGetValue("GalleryRoiTop", out double rt) &&
flow.DoubleParams.TryGetValue("GalleryRoiWidth", out double rw) &&
flow.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();
}
return GalleryClassifierHandler.Extractor.Extract(roiCloned ?? func.Src);
}
finally
{
roiCloned?.Dispose();
}
}
private void AfterGalleryTrain(string action, FeatureGallery gallery)
{
UpdateGalleryProperties(gallery);
RefreshGalleryResult(gallery);
GalleryStatus = $"{action} OK:{gallery.OkCount} NG:{gallery.NgCount}";
}
private void RefreshGalleryResult(FeatureGallery gallery)
{
var func = SelectedVisionFunction;
if (func?.Src == null || func.Src.Empty())
return;
var feature = GalleryClassifierHandler.Extractor.Extract(func.Src);
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);
func.DrawCommands.Clear();
_ = func.RenderDrawAsync();
}
private void UpdateGalleryProperties(FeatureGallery gallery)
{
GalleryOkCount = gallery.OkCount;
GalleryNgCount = gallery.NgCount;
}
#endregion 内部
#endregion 画廊分类
}
}