feat(App): SOP 页 — 画面+ROI 覆盖层 + 步骤卡 + Top3 违规 + 日志 + 运行控制

- ViewModel 构造注入引擎三件套,需在 RegisterTypes 显式注册(反射扫描只覆盖本程序集)
- 帧 Mat 只在采集线程事件存活期内有效,必须当场克隆再交给渲染定时器
- ROI 覆盖层用 Viewbox 内层 Grid = 帧像素尺寸,配方坐标天然对齐
- WritePixels 的 rect 是(宽,高),与 OpenCvSharp 的 Rows/Cols 相反
- 纯 WPF 样式,无 HandyControl / SkiaSharp.Views.WPF
This commit is contained in:
sophelper 2026-11-03 01:21:58 +08:00
parent b75684b254
commit 6e5555994d
3 changed files with 852 additions and 16 deletions

View File

@ -5,7 +5,11 @@ using System.Windows.Threading;
using Prism.Ioc;
using Prism.Mvvm;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Models;
using SopHelper.VVMs.SopPage;
using SopHelper.VVMs.MainWindow;
namespace SopHelper;
@ -39,6 +43,15 @@ public partial class App
}
_ = containerRegistry.RegisterSingleton<NavigationModel>();
// 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集,
// 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。
_ = containerRegistry.RegisterSingleton<ICameraService, UvcCameraService>();
_ = containerRegistry.RegisterSingleton<DetectionPipeline>();
_ = containerRegistry.RegisterSingleton<SopEngine>();
// ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册
_ = containerRegistry.Register<SopPageViewModel>();
}
/// <summary>

View File

@ -2,13 +2,263 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
prism:ViewModelLocator.AutoWireViewModel="True"
Background="{StaticResource Bg}">
<Border>
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Style="{StaticResource Title}" Text="SOP 辅助" HorizontalAlignment="Center" />
<TextBlock Text="{Binding Status}" HorizontalAlignment="Center" Margin="0,10,0,0"
Foreground="{StaticResource FgDim}" />
</StackPanel>
</Border>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="390" />
</Grid.ColumnDefinitions>
<!-- ================= 画面(ROI 覆盖层与画面同一坐标系) ================= -->
<Border Grid.Column="0">
<Viewbox Stretch="Uniform" Margin="4">
<!-- 内层 Grid 尺寸 = 帧像素尺寸,Viewbox 整体缩放,ROI 的像素坐标因此天然对齐 -->
<Grid Width="{Binding FrameWidth}" Height="{Binding FrameHeight}">
<Image Source="{Binding Frame}" Stretch="Fill" />
<ItemsControl ItemsSource="{Binding Rois}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="{Binding W}" Height="{Binding H}"
BorderBrush="{Binding Brush}" BorderThickness="2"
Background="Transparent" Padding="0" CornerRadius="0">
<TextBlock Text="{Binding Name}" Foreground="{Binding Brush}"
FontSize="12" Margin="2,0,0,0"
VerticalAlignment="Top" HorizontalAlignment="Left" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Viewbox>
</Border>
<!-- ================= 右侧控制 ================= -->
<Grid Grid.Column="1" Margin="10,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- 参数 -->
<Border Grid.Row="0">
<StackPanel>
<TextBlock Style="{StaticResource Title}" Text="参数" />
<Grid Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="相机" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding Cameras}"
SelectedItem="{Binding SelectedCamera}"
DisplayMemberPath="Name" />
<Button Grid.Column="2" Content="刷新" Margin="6,0,0,0" Padding="10,4"
Command="{Binding RefreshCamerasCommand}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="配方" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center"
ItemsSource="{Binding Recipes}"
SelectedItem="{Binding SelectedRecipe}" />
<Button Grid.Column="2" Content="应用" Margin="6,0,0,0" Padding="10,4"
Command="{Binding ApplyRecipeCommand}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="44" />
</Grid.ColumnDefinitions>
<TextBlock Text="阈值" Width="40" />
<Slider Grid.Column="1" Minimum="0.1" Maximum="0.95"
TickFrequency="0.05" IsSnapToTickEnabled="True"
Value="{Binding Confidence}" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="{Binding Confidence, StringFormat={}{0:F2}}"
HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="44" />
</Grid.ColumnDefinitions>
<TextBlock Text="抽帧" Width="40" />
<Slider Grid.Column="1" Minimum="1" Maximum="10"
TickFrequency="1" IsSnapToTickEnabled="True"
Value="{Binding FrameStride}" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="{Binding FrameStride}"
HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
</Grid>
<WrapPanel Margin="0,10,0,0">
<TextBlock Text="状态" Width="40" />
<TextBlock Text="{Binding StatusText}" Foreground="{StaticResource Accent}" />
<TextBlock Text="耗时" Margin="16,0,6,0" />
<TextBlock Text="{Binding InferenceText}" Foreground="{StaticResource FgDim}" />
<TextBlock Text="帧率" Margin="16,0,6,0" />
<TextBlock Text="{Binding FpsText}" Foreground="{StaticResource FgDim}" />
</WrapPanel>
</StackPanel>
</Border>
<!-- 运行控制 -->
<WrapPanel Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Left">
<Button Content="开始 / 停止" Command="{Binding StartStopCommand}" />
<Button Content="暂停" Margin="6,0,0,0" Command="{Binding TogglePauseCommand}" />
<Button Content="复位" Margin="6,0,0,0" Command="{Binding ResetCommand}" />
<Button Content="快照" Margin="6,0,0,0" Command="{Binding SnapshotCommand}" />
</WrapPanel>
<!-- 违规 Top3 -->
<Border Grid.Row="2" Margin="0,10,0,0">
<StackPanel>
<TextBlock Style="{StaticResource Title}" Text="违规 Top3" />
<ItemsControl ItemsSource="{Binding Violations}" Margin="0,8,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{StaticResource Ng}" TextTrimming="CharacterEllipsis">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:HH:mm:ss} {1}">
<Binding Path="Time" />
<Binding Path="Message" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- 步骤卡 -->
<Border Grid.Row="3" Margin="0,10,0,0">
<StackPanel>
<TextBlock Style="{StaticResource Title}" Text="步骤" />
<ItemsControl ItemsSource="{Binding StepCards}" Margin="0,8,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border x:Name="card" Padding="8,6" Margin="0,0,0,6"
Background="{StaticResource Bg}"
BorderBrush="{StaticResource Line}" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<TextBlock Width="28" FontWeight="Bold" Foreground="{StaticResource FgDim}"
Text="{Binding StepId, StringFormat={}{0}.}" />
<TextBlock Width="140" Text="{Binding Name}" />
<TextBlock Text="{Binding Message}" Foreground="{StaticResource FgDim}"
TextTrimming="CharacterEllipsis" />
<Rectangle x:Name="dot" Width="8" Height="8" Margin="8,0,0,0"
VerticalAlignment="Center" Fill="{StaticResource Ok}"
Visibility="Collapsed" />
</StackPanel>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsMet}" Value="True">
<Setter TargetName="dot" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsCurrent}" Value="True">
<Setter TargetName="card" Property="BorderBrush" Value="{StaticResource Accent}" />
<Setter TargetName="card" Property="BorderThickness" Value="2" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- 日志 -->
<Border Grid.Row="4" Margin="0,10,0,0" Padding="6">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Style="{StaticResource Title}" Text="日志" />
<ListBox Grid.Row="1" Margin="0,8,0,0"
Background="Transparent" BorderThickness="0"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="False"
ItemsSource="{Binding Logs}">
<ListBox.ItemContainerStyle>
<!-- 全局 ListBox 样式给的是导航用的模板,这里要普通列表 -->
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="0,1" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="12" TextWrapping="Wrap">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:HH:mm:ss} [{1}] {2}">
<Binding Path="Time" />
<Binding Path="Level" />
<Binding Path="Message" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
<!-- 连接指示 -->
<StackPanel Grid.Row="5" Orientation="Horizontal" Margin="0,10,0,0">
<Ellipse Width="10" Height="10">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="{StaticResource Line}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsConnected}" Value="True">
<Setter Property="Fill" Value="{StaticResource Ok}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
<TextBlock Text="相机未连接" Margin="6,0,0,0" Foreground="{StaticResource FgDim}" />
</StackPanel>
</Grid>
</Grid>
</UserControl>

View File

@ -1,20 +1,593 @@
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using Prism.Commands;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
namespace SopHelper.VVMs.SopPage;
/// <summary>
/// SOP 主页视图模型(占位,画面与步骤卡在 s5 填充)
/// SOP 主页视图模型:相机 → 推理管线 → SOP 引擎,界面只订阅事件。
/// </summary>
public class SopPageViewModel : BindableBase
public class SopPageViewModel : ViewModelBase
{
private string _status = "骨架已就绪(s2)";
private const int MaxLogLines = 300;
private const int MaxTopViolations = 3;
private readonly ICameraService _camera;
private readonly DetectionPipeline _pipeline;
private readonly SopEngine _engine;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _renderTimer;
/// <summary>采集线程写、UI 线程取最新帧</summary>
private readonly object _frameLock = new();
private Mat? _pending;
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
private FrameResult? _lastFrame;
private WriteableBitmap? _bitmap;
private long _frameCount;
private long _lastTickCount;
private CameraInfo? _selectedCamera;
private string? _selectedRecipe;
private ImageSource? _frame;
private string _statusText = "就绪";
private string _fpsText = "—";
private string _inferenceText = "—";
private bool _isRunning;
private bool _isConnected;
private double _frameWidth;
private double _frameHeight;
private double _confidence = 0.6;
private int _frameStride = 2;
/// <summary>
/// 状态文本
/// SOP 主页视图模型
/// </summary>
public string Status
public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine)
{
get { return _status; }
set { SetProperty(ref _status, value); }
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_dispatcher = Dispatcher.CurrentDispatcher;
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() => IsConnected = on);
_camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message));
_pipeline.ResultArrived += result => _dispatcher.BeginInvoke(() => OnResult(result));
// 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆
_camera.FrameArrived += OnCameraFrame;
_engine.LogArrived += entry => _dispatcher.BeginInvoke(() => AppendLog(entry));
_engine.ViolationRaised += violation => _dispatcher.BeginInvoke(() => AppendViolation(violation));
_engine.StepSnapshotChanged += snapshot => _dispatcher.BeginInvoke(() => UpdateCard(snapshot));
_engine.Completed += () => _dispatcher.BeginInvoke(() => StatusText = "本轮完成");
// 渲染定时器:从采集线程留下的最新帧取一份画出来(天然限帧,不在采集线程做 UI 活)
_renderTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(40) };
_renderTimer.Tick += (_, _) => RenderFrame();
_renderTimer.Start();
LoadRecipes();
// 命令接线(DelegateCommand 的可用条件都挂在这里)
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => !IsRunning);
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning);
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
StatusText = "选择相机和配方,点开始";
}
/// <summary>可用相机</summary>
public ObservableCollection<CameraInfo> Cameras { get; } = [];
/// <summary>可用配方文件</summary>
public ObservableCollection<string> Recipes { get; } = [];
/// <summary>步骤卡</summary>
public ObservableCollection<StepCard> StepCards { get; } = [];
/// <summary>Top3 违规</summary>
public ObservableCollection<ViolationItem> Violations { get; } = [];
/// <summary>日志</summary>
public ObservableCollection<LogItem> Logs { get; } = [];
/// <summary>画面 ROI</summary>
public ObservableCollection<RoiItem> Rois { get; } = [];
/// <summary>选中相机</summary>
public CameraInfo? SelectedCamera
{
get { return _selectedCamera; }
set { SetProperty(ref _selectedCamera, value); }
}
/// <summary>选中配方</summary>
public string? SelectedRecipe
{
get { return _selectedRecipe; }
set { SetProperty(ref _selectedRecipe, value); }
}
/// <summary>画面</summary>
public ImageSource? Frame
{
get { return _frame; }
set { SetProperty(ref _frame, value); }
}
/// <summary>状态</summary>
public string StatusText
{
get { return _statusText; }
set { SetProperty(ref _statusText, value); }
}
/// <summary>结果帧率</summary>
public string FpsText
{
get { return _fpsText; }
set { SetProperty(ref _fpsText, value); }
}
/// <summary>推理耗时</summary>
public string InferenceText
{
get { return _inferenceText; }
set { SetProperty(ref _inferenceText, value); }
}
/// <summary>是否运行中</summary>
public bool IsRunning
{
get { return _isRunning; }
set { SetProperty(ref _isRunning, value); }
}
/// <summary>相机是否已连接</summary>
public bool IsConnected
{
get { return _isConnected; }
set { SetProperty(ref _isConnected, value); }
}
/// <summary>画面像素宽(ROI 覆盖层按它缩放)</summary>
public double FrameWidth
{
get { return _frameWidth; }
set { SetProperty(ref _frameWidth, value); }
}
/// <summary>画面像素高</summary>
public double FrameHeight
{
get { return _frameHeight; }
set { SetProperty(ref _frameHeight, value); }
}
/// <summary>置信度阈值(透传给 YOLO)</summary>
public double Confidence
{
get { return _confidence; }
set { SetProperty(ref _confidence, value); }
}
/// <summary>抽帧间隔</summary>
public int FrameStride
{
get { return _frameStride; }
set { SetProperty(ref _frameStride, value); }
}
/// <summary>刷新相机列表</summary>
public DelegateCommand RefreshCamerasCommand { get; private set; } = null!;
/// <summary>开始 / 停止</summary>
public DelegateCommand StartStopCommand { get; private set; } = null!;
/// <summary>暂停 / 继续</summary>
public DelegateCommand TogglePauseCommand { get; private set; } = null!;
/// <summary>复位</summary>
public DelegateCommand ResetCommand { get; private set; } = null!;
/// <summary>应用配方</summary>
public DelegateCommand ApplyRecipeCommand { get; private set; } = null!;
/// <summary>快照</summary>
public DelegateCommand SnapshotCommand { get; private set; } = null!;
private bool CanStart() => SelectedCamera is not null || IsRunning;
/// <summary>
/// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期
/// </summary>
private void OnCameraFrame(CameraFrame frame)
{
var clone = frame.Bgr.Clone();
lock (_frameLock)
{
var old = _pending;
_pending = clone;
old?.Dispose();
}
}
/// <summary>
/// 快照:把最近处理过的帧连同 ROI 存到 snaps/
/// </summary>
private void Snapshot()
{
var frame = _lastFrame;
if (frame is null) return;
lock (_frameLock)
{
if (_pending is null) return;
var dir = Path.Combine(AppContext.BaseDirectory, "snaps");
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, $"{frame.FrameId}_{frame.Timestamp:HHmmss_fff}.png");
Cv2.ImWrite(path, _pending);
Log("info", $"快照已存:{path}");
}
}
/// <inheritdoc />
public override void Destroy()
{
_renderTimer.Stop();
lock (_frameLock)
{
_pending?.Dispose();
_pending = null;
}
_pipeline.Dispose();
_camera.Dispose();
base.Destroy();
}
/// <summary>
/// 扫描 configs/sop/*.yaml
/// </summary>
private void LoadRecipes()
{
var dir = Path.Combine(AppContext.BaseDirectory, "configs", "sop");
if (!Directory.Exists(dir)) return;
foreach (var file in Directory.GetFiles(dir, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
}
private async Task RefreshCamerasAsync()
{
Cameras.Clear();
foreach (var info in await _camera.EnumerateAsync())
Cameras.Add(info);
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到 UVC 相机");
return;
}
SelectedCamera = Cameras[0];
Log("info", $"枚举到 {Cameras.Count} 个相机");
}
private async Task StartStopAsync()
{
if (IsRunning)
{
_pipeline.Stop();
IsRunning = false;
StatusText = "已停止";
return;
}
if (SelectedCamera is null)
{
Log("warn", "先选相机");
return;
}
if (string.IsNullOrWhiteSpace(SelectedRecipe))
{
Log("warn", "先选配方");
return;
}
if (!await _camera.ConnectAsync(SelectedCamera)) return;
ApplyRecipe();
// 阈值 / 抽帧从界面参数覆盖配方默认值
_pipeline.SetThresholds((float)Confidence, 0.45f);
_engine.Config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
if (!await _pipeline.StartAsync())
{
Log("warn", "采集启动失败");
return;
}
_engine.Start();
IsRunning = true;
StatusText = "运行中";
}
private void ApplyRecipe()
{
if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
var path = Path.Combine(AppContext.BaseDirectory, "configs", "sop", SelectedRecipe);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
return;
}
var config = SopConfigLoader.Load(path);
_engine.Load(config);
// 模型:配方写了就用配方的,没写就跳过(只有手部/计时类条件能工作)
var options = new PipelineOptions
{
YoloModelPath = ResolveModel(config.Sop.Model?.Path),
YoloClasses = config.Sop.Model?.Classes ?? [],
YoloInputSize = config.Sop.Model?.InputSize ?? 640,
PalmModelPath = ResolveModel("models/palm_detection_full.onnx"),
LandmarkModelPath = ResolveModel("models/hand_landmark_full.onnx"),
FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
};
_pipeline.LoadModels(options);
StepCards.Clear();
Rois.Clear();
foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
StepCards.Add(new StepCard { StepId = step.Id, Name = step.Name, Message = "—" });
foreach (var (name, def) in config.Sop.Regions)
Rois.Add(new RoiItem { Name = name, X = def.X1, Y = def.Y1, W = def.X2 - def.X1, H = def.Y2 - def.Y1, ColorHex = def.Color });
foreach (var warning in config.Warnings)
Log("warn", warning);
Log("info", $"配方已加载:{config.Sop.Name}({StepCards.Count} 步 / {Rois.Count} 区域)");
foreach (var warning in _pipeline.Warnings)
Log("warn", warning);
}
/// <summary>
/// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
/// </summary>
private static string? ResolveModel(string? relative)
{
if (string.IsNullOrWhiteSpace(relative)) return null;
var path = Path.IsPathRooted(relative) ? relative : Path.Combine(AppContext.BaseDirectory, relative);
return File.Exists(path) ? path : null;
}
private void OnResult(FrameResult result)
{
lock (_frameLock)
{
_lastFrame = result;
}
_engine.ProcessFrame(result);
InferenceText = $"{result.InferenceMs:F1} ms";
}
/// <summary>
/// 渲染定时器:取采集线程留下的最新帧
/// </summary>
private void RenderFrame()
{
Mat? src;
lock (_frameLock)
{
src = _pending;
_pending = null;
}
if (src is null) return;
_frameCount++;
using (src)
{
if (_bitmap is null || _bitmap.PixelWidth != src.Width || _bitmap.PixelHeight != src.Height)
{
_bitmap = new WriteableBitmap(src.Cols, src.Rows, 96, 96, PixelFormats.Bgr24, null);
// ROI 覆盖层的坐标系就是帧像素坐标系,所以内层 Grid 尺寸必须跟着帧走
FrameWidth = src.Cols;
FrameHeight = src.Rows;
}
var bytes = new byte[src.Rows * src.Cols * src.Channels()];
Marshal.Copy(src.Data, bytes, 0, bytes.Length);
// Mat.Step 是方法不是属性;这里按行字节数显式算,别依赖 Mat 的内部 stride
var stride = src.Cols * src.ElemSize();
// 注意:rect 是 (宽, 高),OpenCvSharp 的 Rows/Cols 是 (高, 宽),别写反
_bitmap.WritePixels(new System.Windows.Int32Rect(0, 0, src.Cols, src.Rows), bytes, stride, 0);
}
Frame = _bitmap;
// 帧率:这 40ms 里处理了几帧
var delta = _frameCount - _lastTickCount;
_lastTickCount = _frameCount;
FpsText = $"{delta * 25.0:F1} fps(渲染)";
}
private void UpdateCard(StepSnapshot snapshot)
{
var card = StepCards.FirstOrDefault(c => c.StepId == snapshot.StepId);
if (card is null) return;
card.IsCurrent = snapshot.IsCurrent;
card.IsMet = snapshot.IsMet;
card.Message = snapshot.Message;
}
private void AppendViolation(ViolationEvent violation)
{
Violations.Insert(0, new ViolationItem
{
Time = violation.At,
StepId = violation.StepId,
Type = violation.Type,
Message = violation.Message,
});
while (Violations.Count > MaxTopViolations)
Violations.RemoveAt(Violations.Count - 1);
}
private void AppendLog(LogEntry entry)
{
Logs.Add(new LogItem { Time = entry.At, Level = entry.Level, Message = entry.Message });
while (Logs.Count > MaxLogLines)
Logs.RemoveAt(0);
}
private void Log(string level, string message)
{
AppendLog(new LogEntry { Level = level, Message = message });
}
}
/// <summary>
/// 步骤卡数据
/// </summary>
public class StepCard : ViewModelBase
{
private bool _isCurrent;
private bool _isMet;
private string _message = "";
/// <summary>步骤 Id</summary>
public int StepId { get; set; }
/// <summary>步骤名</summary>
public string Name { get; set; } = "";
/// <summary>当前步骤</summary>
public bool IsCurrent
{
get { return _isCurrent; }
set { SetProperty(ref _isCurrent, value); }
}
/// <summary>已完成</summary>
public bool IsMet
{
get { return _isMet; }
set { SetProperty(ref _isMet, value); }
}
/// <summary>判定说明</summary>
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
}
/// <summary>
/// Top3 违规条目
/// </summary>
public class ViolationItem
{
/// <summary>时刻</summary>
public DateTime Time { get; set; }
/// <summary>步骤 Id</summary>
public int StepId { get; set; }
/// <summary>类型</summary>
public string Type { get; set; } = "";
/// <summary>文案</summary>
public string Message { get; set; } = "";
}
/// <summary>
/// 日志条目
/// </summary>
public class LogItem
{
/// <summary>时刻</summary>
public DateTime Time { get; set; }
/// <summary>级别 info/warn/viol</summary>
public string Level { get; set; } = "info";
/// <summary>文案</summary>
public string Message { get; set; } = "";
}
/// <summary>
/// ROI 覆盖层条目(坐标 = 配方像素坐标,外层 Viewbox 负责缩放)
/// </summary>
public class RoiItem
{
/// <summary>区域名</summary>
public string Name { get; set; } = "";
/// <summary>X</summary>
public double X { get; set; }
/// <summary>Y</summary>
public double Y { get; set; }
/// <summary>W</summary>
public double W { get; set; }
/// <summary>H</summary>
public double H { get; set; }
/// <summary>颜色(#RRGGBB)。不叫 Color——会和 System.Windows.Media.Color 撞名</summary>
public string ColorHex { get; set; } = "#4CAF50";
/// <summary>画刷</summary>
public SolidColorBrush Brush => new((System.Windows.Media.Color)ColorConverter.ConvertFromString(ColorHex));
}