#nullable enable using OpenCvSharp; using PLCSharp.Core.UserControls; using PLCSharp.VVMs.Vision.GalleryClassifier; using PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm; using Prism.Commands; using System; using System.IO; using System.Windows.Input; namespace PLCSharp.VVMs.Vision { /// /// 视觉流程配置界面 —— 画廊分类的训练命令 /// public partial class VisionConfigViewModel { #region 画廊分类 // 撤销状态(只记上一步,跟 SelectVisionFlow 绑定) private string? _lastGalleryAction; 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; 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 #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 && GalleryClassifierHandler.SharedEmbedding != null; } private FeatureGallery GetGallery() { var flow = SelectVisionFlow ?? throw new InvalidOperationException("未选择步骤"); var dim = GalleryClassifierHandler.SharedEmbedding?.FeatureDimension ?? throw new InvalidOperationException("模型未加载"); return GalleryClassifierHandler.LoadFromData(flow, dim); } 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; if (GalleryClassifierHandler.SharedEmbedding == null) return; var json = File.ReadAllText(dialog.FileName); var data = System.Text.Json.JsonSerializer.Deserialize(json); if (data == null) return; var gallery = new FeatureGallery(GalleryClassifierHandler.SharedEmbedding.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; } var embedding = GalleryClassifierHandler.SharedEmbedding; if (embedding == null) 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 embedding.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() || GalleryClassifierHandler.SharedEmbedding == null) return; var feature = GalleryClassifierHandler.SharedEmbedding.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 } }