using OpenCvSharp;
using OpenCvSharp.WpfExtensions;
using PLCSharp.Core.Common;
using PLCSharp.Core.Prism;
using PLCSharp.Core.Tools;
using PLCSharp.Core.UserControls;
using PLCSharp.Models;
using PLCSharp.VVMs.Connects;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.Vision.Camera;
using PLCSharp.VVMs.Vision.VisionFlowHandler;
using PLCSharp.VVMs.Vision.VisionFlowHandler.Access;
using PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm;
using PLCSharp.VVMs.Vision.VisionFlowHandler.Processing;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace PLCSharp.VVMs.Vision
{
///
/// 视觉流程配置界面的视图模型,管理流程步骤的增删、参数编辑和功能测试
///
public class VisionConfigViewModel : DialogAwareBase
{
private readonly IDialogService _dialogService;
///
/// Vision配置视图模型
///
public VisionConfigViewModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
{
_dialogService = dialogService;
GlobalModel = container.Resolve();
VisionsModel = GlobalModel.VisionsModel;
SystemVariables = GlobalModel.VariablesModel.SystemVariables;
Connects = GlobalModel.Connects;
FlowMenuGroups = BuildFlowMenuGroups();
ImageEdit = new ImageEdit();
Binding binding = new("ImgSrc");
ImageEdit.DataContext = this;
ImageEdit.SetBinding(ImageEdit.ImageSourceProperty, binding);
}
private ImageEdit _ImageEdit;
///
///
///
public ImageEdit ImageEdit
{
get { return _ImageEdit; }
set { SetProperty(ref _ImageEdit, value); }
}
///
/// 打开对话框后要执行的
///
/// parameters
public override void OnDialogOpened(IDialogParameters parameters)
{
SelectedVisionFunction = parameters.GetValue("SelectedVisionFunction");
SelectedVisionFunction.EditImageEdit = ImageEdit;
} ///
/// 关闭对话框后要执行的
///
public override void OnDialogClosed()
{
SelectedVisionFunction.EditImageEdit = null;
}
#region 视觉流程
private AsyncDelegateCommand _TestFunction;
///
/// 测试Function
///
public AsyncDelegateCommand TestFunction =>
_TestFunction ??= new AsyncDelegateCommand(ExecuteTestFunctionAsync);
private async Task ExecuteTestFunctionAsync()
{
try
{
await Task.Run(() =>
{
var runAllFlow = new FlowModel();
while (true)
{
Thread.Sleep(1);
if (SelectedVisionFunction.RunAll(runAllFlow))
{
return;
}
else if (runAllFlow.CheckFlowTime(10))
{
throw new Exception("流程超时!");
}
}
});
}
catch (Exception ex)
{
SendErr(ex.Message);
}
if (SelectedVisionFunction.Src == null) return;
ShowMat = SelectedVisionFunction.Src;
}
private DelegateCommand _Save;
///
/// 保存
///
public DelegateCommand Save =>
_Save ??= new DelegateCommand(ExecuteSave);
void ExecuteSave()
{
VisionsModel.Manage.Execute("Save");
}
private AsyncDelegateCommand _TestSelect;
///
/// 测试选择
///
public AsyncDelegateCommand TestSelect =>
_TestSelect ??= new AsyncDelegateCommand(ExecuteTestSelectAsync);
private async Task ExecuteTestSelectAsync()
{
try
{
if (SelectVisionFlow == null) return;
await Task.Run(() =>
{
SelectVisionFlow.Flow.Reset();
while (true)
{
Thread.Sleep(1);
if (SelectedVisionFunction.RunItem(SelectVisionFlow))
{
return;
}
else if (SelectVisionFlow.Flow.CheckFlowTime(10))
{
throw new Exception("流程超时!");
}
}
});
}
catch (Exception ex)
{
SendInfoDialog(ex.Message);
}
if (SelectedVisionFunction.Src == null) return;
ShowMat = SelectedVisionFunction.Src;
}
private DelegateCommand _Manage;
///
/// 流程管理
///
public DelegateCommand Manage =>
_Manage ??= new DelegateCommand(ExecuteManage);
void ExecuteManage(string cmd)
{
switch (cmd)
{
case "删除":
if (SelectVisionFlow != null && SelectedVisionFunction.VisionFlows.Contains(SelectVisionFlow))
{
SelectedVisionFunction.VisionFlows.Remove(SelectVisionFlow);
}
break;
case "上移":
if (SelectVisionFlow != null && SelectedVisionFunction.VisionFlows.IndexOf(SelectVisionFlow) > 0)
{
var currentIndex = SelectedVisionFunction.VisionFlows.IndexOf(SelectVisionFlow);
SelectedVisionFunction.VisionFlows.Move(currentIndex, currentIndex - 1);
}
break;
case "下移":
if (SelectVisionFlow != null && SelectedVisionFunction.VisionFlows.IndexOf(SelectVisionFlow) < SelectedVisionFunction.VisionFlows.Count - 1)
{
var currentIndex = SelectedVisionFunction.VisionFlows.IndexOf(SelectVisionFlow);
SelectedVisionFunction.VisionFlows.Move(currentIndex, currentIndex + 1);
}
break;
}
}
///
/// 添加流程菜单项——按 分组
///
public List FlowMenuGroups { get; }
private static List BuildFlowMenuGroups()
{
return [.. Enum.GetValues()
.Select(t => (Type: t, Category: GetCategory(t)))
.GroupBy(x => x.Category)
.Select(g => new FlowMenuGroup
{
Header = g.Key,
Items = [.. g.Select(x => new FlowMenuItem { Header = x.Type.ToString(), FlowType = x.Type })]
})];
}
private static string GetCategory(VisionFlowType type)
{
var field = typeof(VisionFlowType).GetField(type.ToString());
return field?.GetCustomAttribute()?.Category ?? "其他";
}
private DelegateCommand _AddFlow;
///
/// 添加Flow
///
public DelegateCommand AddFlow =>
_AddFlow ??= new DelegateCommand(ExecuteAddFlow);
void ExecuteAddFlow(string cmd)
{
if (Enum.TryParse(cmd, out VisionFlowType visionFlowType))
{
var newFlow = new VisionFlow() { Type = visionFlowType };
SelectedVisionFunction.VisionFlows.Add(newFlow);
switch (visionFlowType)
{
case VisionFlowType.从全局图像获取图片:
break;
case VisionFlowType.从文件获取图片:
break;
case VisionFlowType.拍照:
break;
case VisionFlowType.阈值:
newFlow.IntParams["ThresholdType"] = 0;
newFlow.IntParams["Threshold"] = 100;
newFlow.IntParams["MaxValue"] = 255;
newFlow.BoolParams["IsOtsu"] = false;
newFlow.BoolParams["IsTriangle"] = false;
break;
case VisionFlowType.GRAY2BGR:
break;
case VisionFlowType.BGR2GRAY:
break;
case VisionFlowType.存到全局图像:
break;
case VisionFlowType.存到文件:
break;
case VisionFlowType.各通道最小值:
break;
case VisionFlowType.各通道最大值:
break;
case VisionFlowType.显示图像到主页:
break;
case VisionFlowType.卡尺寻边:
newFlow.IntParams["Threshold"] = 30;
newFlow.IntParams["Direction"] = 0;
newFlow.IntParams["EdgeSelector"] = 0;
newFlow.IntParams["MinScore"] = 10;
newFlow.DoubleParams["RansacTh"] = 5;
newFlow.IntParams["CaliperLength"] = 100;
newFlow.IntParams["NumCalipers"] = 50;
break;
case VisionFlowType.卡尺找圆:
newFlow.IntParams["Threshold"] = 30;
newFlow.IntParams["Direction"] = 0;
newFlow.IntParams["CaliperDirection"] = 0;
newFlow.IntParams["EdgeSelector"] = 0;
newFlow.IntParams["MinInliers"] = 10;
newFlow.DoubleParams["RansacTh"] = 5;
newFlow.IntParams["MinScore"] = 10;
newFlow.IntParams["NumCalipers"] = 50;
newFlow.IntParams["CaliperLength"] = 100;
break;
case VisionFlowType.卡尺找旋转矩形:
newFlow.IntParams["Threshold"] = 30;
newFlow.IntParams["Direction"] = 0;
newFlow.IntParams["CaliperDirection"] = 0;
newFlow.IntParams["EdgeSelector"] = 0;
newFlow.IntParams["MinInliers"] = 10;
newFlow.DoubleParams["RansacTh"] = 5;
newFlow.IntParams["MinScore"] = 10;
newFlow.IntParams["NumCalipers"] = 50;
newFlow.IntParams["CaliperLength"] = 100;
break;
case VisionFlowType.ORB匹配:
newFlow.IntParams["NFeatures"] = 500;
newFlow.IntParams["MinMatches"] = 8;
newFlow.DoubleParams["MinGoodRatio"] = 0.3;
newFlow.StringParams["TemplateName"] = "ORB_Template";
break;
case VisionFlowType.取通道:
newFlow.IntParams["ChannelIndex"] = 0;
break;
case VisionFlowType.坐标转换:
newFlow.DoubleParams["CalibSpacing"] = 5;
newFlow.DoubleParams["ImageX"] = 0;
newFlow.DoubleParams["ImageY"] = 0;
newFlow.StringParams["TransformMat"] = "";
break;
case VisionFlowType.图像翻转:
newFlow.IntParams["FlipDirection"] = 0;
break;
case VisionFlowType.图像旋转:
newFlow.DoubleParams["RotateAngle"] = 0;
newFlow.IntParams["ResizeMode"] = 0;
break;
case VisionFlowType.ROI剪切:
break;
case VisionFlowType.ROI解码:
newFlow.IntParams["DecodeType"] = 0;
newFlow.BoolParams["EnableMirror"] = false;
newFlow.BoolParams["EnableUpscale"] = true;
newFlow.BoolParams["UsePureBarcode"] = false;
newFlow.StringParams["ResultVarName"] = "条码解码_Result";
break;
case VisionFlowType.微信解码:
newFlow.BoolParams["EnableMirror"] = false;
newFlow.StringParams["ResultVarName"] = "微信解码_Result";
break;
case VisionFlowType.颜色面积:
newFlow.IntParams["HMin"] = 0;
newFlow.IntParams["HMax"] = 180;
newFlow.IntParams["SMin"] = 0;
newFlow.IntParams["SMax"] = 255;
newFlow.IntParams["VMin"] = 0;
newFlow.IntParams["VMax"] = 255;
newFlow.DoubleParams["AreaMinPercent"] = 0;
newFlow.DoubleParams["AreaMaxPercent"] = 100;
newFlow.StringParams["ResultVarName"] = "颜色面积_Result";
break;
case VisionFlowType.灰度面积:
newFlow.IntParams["GrayMin"] = 0;
newFlow.IntParams["GrayMax"] = 255;
newFlow.DoubleParams["AreaMinPercent"] = 0;
newFlow.DoubleParams["AreaMaxPercent"] = 100;
newFlow.StringParams["ResultVarName"] = "灰度面积_Result";
break;
default:
break;
}
SelectVisionFlow = null;
SelectImageData = null;
}
}
#endregion
#region 其它模型
///
/// 连接模型
///
public ConnectsModel Connects { get; set; }
///
/// 全局模型
///
public GlobalModel GlobalModel { get; set; }
///
/// 系统全局变量集合
///
public ObservableCollection SystemVariables { get; set; }
private CameraBase _SelectedCamera;
///
/// 选中的相机
///
public CameraBase SelectedCamera
{
get { return _SelectedCamera; }
set
{
SetProperty(ref _SelectedCamera, value);
if (value != null)
SelectVisionFlow.StringParams["Camera"] = value.Name;
}
}
private SystemVariable _SelectedSystemVariable;
///
/// 选中的全局变量
///
public SystemVariable SelectedSystemVariable
{
get { return _SelectedSystemVariable; }
set
{
SetProperty(ref _SelectedSystemVariable, value);
}
}
private Variable _FlowSelectedVariable;
///
/// 在流程中选择的全局变量
///
public Variable FlowSelectedVariable
{
get { return _FlowSelectedVariable; }
set
{
SetProperty(ref _FlowSelectedVariable, value);
if (value != null && SelectVisionFlow != null)
SelectVisionFlow.StringParams["Variable"] = value.Name;
}
}
private ImageData _SelectImageData;
///
/// 选择图像数据
///
public ImageData SelectImageData
{
get { return _SelectImageData; }
set
{
SetProperty(ref _SelectImageData, value);
if (value != null)
SelectVisionFlow.StringParams["Image"] = value.Name;
}
}
private UserControl _ContentRegion;
///
/// 内容区域
///
public UserControl ContentRegion
{
get { return _ContentRegion; }
set { SetProperty(ref _ContentRegion, value); }
}
///
/// 视觉模型
///
public VisionsModel VisionsModel { get; set; }
private VisionFunction _SelectedVisionFunction;
///
/// SelectedVisionFunction
///
public VisionFunction SelectedVisionFunction
{
get { return _SelectedVisionFunction; }
set { SetProperty(ref _SelectedVisionFunction, value); }
}
///
/// Line 类型局部变量列表(供 ComboBox 选择)
///
public IEnumerable LineVariables =>
SelectedVisionFunction?.Params?.Variables?.Where(v => v.VarType == "Line") ?? [];
public IEnumerable AllVariables =>
SelectedVisionFunction?.Params?.Variables ?? [];
private VisionFlow _SelectVisionFlow;
///
/// 选择VisionFlow
///
public VisionFlow SelectVisionFlow
{
get { return _SelectVisionFlow; }
set
{
SetProperty(ref _SelectVisionFlow, value);
ContentRegion = null;
if (_SelectVisionFlow != null)
{
_SelectVisionFlow_TypeChanged();
}
}
}
private void _SelectVisionFlow_TypeChanged()
{
ContentRegion = null;
switch (_SelectVisionFlow.Type)
{
case VisionFlowType.从全局图像获取图片:
case VisionFlowType.存到全局图像:
ContentRegion = new ImagesPool();
break;
case VisionFlowType.从局部图像获取图片:
case VisionFlowType.存到局部图像:
ContentRegion = new ProcessImageSelector();
SelectedMat = null;
break;
case VisionFlowType.从文件获取图片:
ContentRegion = new ImageFromFile();
break;
case VisionFlowType.拍照:
ContentRegion = new ImageFromCamera();
break;
case VisionFlowType.阈值:
ContentRegion = new Threshold();
break;
case VisionFlowType.GRAY2BGR:
break;
case VisionFlowType.BGR2GRAY:
break;
case VisionFlowType.存到文件:
ContentRegion = new ImageToFile();
break;
case VisionFlowType.各通道最小值:
break;
case VisionFlowType.各通道最大值:
break;
case VisionFlowType.显示图像到主页:
ContentRegion = new ImageToHomePage();
break;
case VisionFlowType.卡尺寻边:
ContentRegion = new CaliperEdgeFind();
break;
case VisionFlowType.卡尺找圆:
ContentRegion = new CaliperFindCircle();
break;
case VisionFlowType.卡尺找旋转矩形:
ContentRegion = new CaliperFindRect();
break;
case VisionFlowType.两线交点:
ContentRegion = new TwoLineIntersect();
break;
case VisionFlowType.ORB匹配:
ContentRegion = new ORBMatch();
break;
case VisionFlowType.取通道:
ContentRegion = new SplitChannel();
break;
case VisionFlowType.坐标转换:
ContentRegion = new CoordTransform();
break;
case VisionFlowType.图像翻转:
ContentRegion = new ImageFlip();
break;
case VisionFlowType.图像旋转:
ContentRegion = new ImageRotate();
break;
case VisionFlowType.ROI剪切:
ContentRegion = new ROICrop();
break;
case VisionFlowType.ROI解码:
ContentRegion = new BarcodeDecode();
break;
case VisionFlowType.微信解码:
ContentRegion = new WeChatDecode();
break;
case VisionFlowType.颜色面积:
ContentRegion = new ColorArea();
break;
case VisionFlowType.灰度面积:
ContentRegion = new GrayArea();
break;
}
if (ContentRegion != null)
ContentRegion.DataContext = this;
}
#endregion
#region 局部图像管理
private DelegateCommand _MatManage;
///
/// 局部图像管理
///
public DelegateCommand MatManage =>
_MatManage ??= new DelegateCommand(ExecuteMatManage);
void ExecuteMatManage(string cmd)
{
if (SelectedVisionFunction == null) return;
switch (cmd)
{
case "New":
var baseName = "temp";
int index = 1;
while (SelectedVisionFunction.Params.Mats.Where(w => w.Name == $"{baseName}{index}").Any())
index++;
SelectedVisionFunction.Params.Mats.Add(new ImageData { Name = $"{baseName}{index}" });
break;
case "Remove":
if (GridSelectedMat == null) return;
if (SelectedVisionFunction.Params.Mats.Contains(GridSelectedMat))
SelectedVisionFunction.Params.Mats.Remove(GridSelectedMat);
break;
case "Show":
if (GridSelectedMat.Mat != null && GridSelectedMat.Mat.Empty() == false)
ShowMat = GridSelectedMat.Mat;
break;
}
}
private ImageData _SelectedMat;
///
/// 在流程中选择的全局图像
///
public ImageData SelectedMat
{
get { return _SelectedMat; }
set
{
SetProperty(ref _SelectedMat, value);
if (value != null)
SelectVisionFlow.StringParams["Image"] = value.Name;
}
}
private ImageData _GridSelectedMat;
///
/// 在表格中选择的全局图像
///
public ImageData GridSelectedMat
{
get { return _GridSelectedMat; }
set { SetProperty(ref _GridSelectedMat, value); }
}
#endregion
#region 变量表
private LocalVariableItem _SelectedLocalVariable;
///
/// 局部变量表中选中的行
///
public LocalVariableItem SelectedLocalVariable
{
get { return _SelectedLocalVariable; }
set { SetProperty(ref _SelectedLocalVariable, value); }
}
private DelegateCommand _LocalVariableManage;
///
/// 局部变量表右键菜单命令(AddPoint / AddLine / AddCircle / AddRect / Remove)
///
public DelegateCommand LocalVariableManage =>
_LocalVariableManage ??= new DelegateCommand(ExecuteLocalVariableManage);
void ExecuteLocalVariableManage(string cmd)
{
if (SelectedVisionFunction == null) return;
var vars = SelectedVisionFunction.Params.Variables;
switch (cmd)
{
case "Edit":
if (_SelectedLocalVariable != null)
{
_dialogService.ShowDialog("VariableEditor", new DialogParameters { { "item", _SelectedLocalVariable } }, _ =>
{
});
}
break;
case "AddPoint":
vars.Add(new LocalVariableItem(NextVarName(vars, "point"), "Pos", new Pos()));
break;
case "AddLine":
vars.Add(new LocalVariableItem(NextVarName(vars, "line"), "Line", new Line()));
break;
case "AddCircle":
vars.Add(new LocalVariableItem(NextVarName(vars, "circle"), "Circle", new Circle()));
break;
case "AddRect":
vars.Add(new LocalVariableItem(NextVarName(vars, "rect"), "Rect", new Rect()));
break;
case "Remove":
if (_SelectedLocalVariable != null && vars.Contains(_SelectedLocalVariable))
vars.Remove(_SelectedLocalVariable);
break;
}
}
private static string NextVarName(ObservableCollection vars, string baseName)
{
var existing = vars.Select(v => v.Name).ToHashSet();
int i = 1;
while (existing.Contains($"{baseName}{i}"))
i++;
return $"{baseName}{i}";
}
private DelegateCommand