Keep only the standalone Avalonia application and its shared engine

This commit is contained in:
tfarcraw 2026-11-08 20:32:51 +08:00
parent 102fea1a9b
commit 62d9a1a8a7
85 changed files with 60 additions and 7526 deletions

View File

@ -1,7 +1,7 @@
# SopHelper 统一 Avalonia 跨平台版
入口为 `SopHelper.Avalonia.slnx`。Windows、Linux 都编译 `src/SopHelper.Avalonia`,不存在 Windows/Linux 两份视图或 ViewModel。
现有 WPF `src/SopHelper.App` 保留作为迁移参考,未修改其源码。此前 `SopHelper.Linux` 简化验证版已停止作为部署入口。
原 WPF 仓库已完整归档到 `../archive/SopHelper-WPF-20261108/`。旧 Linux 简化版已删除;当前仓库是唯一活动版本。
## 与原程序的对应关系
@ -13,7 +13,7 @@
| ROI 图像画框、坐标微调、相机取图 | Avalonia `RegionCanvas`,仍保存原图像素坐标 |
| 零件标注、复核、SAM2、导出、YOLO 训练 | `Training`,保留原项目格式与 worker 协议 |
| 相机预览、录像、退出清理 | `Training/CameraWindow`,保留相机互斥与关闭等待流程 |
| SOP、检测器、左右手稳定器、录像器、训练数据与 worker 客户端 | `SopHelper.CrossPlatform.Engine` 直接链接原 `SopHelper.Engine` 源文件 |
| SOP、检测器、左右手稳定器、录像器、训练数据与 worker 客户端 | `SopHelper.CrossPlatform.Engine` 独立保存全部共享引擎源码,不引用归档仓库 |
界面框架相关 API(绘图、图像缓冲、文件选择、UI 调度、窗口关闭)统一由 Avalonia 实现。
ViewModel 不按操作系统分叉。UVC 的 MSMF/DSHOW 与 V4L2、Python 可执行文件路径和原生 SDK 库名,

View File

@ -1,12 +1,12 @@
# SopHelper Linux 部署
当前入口是统一的 **Avalonia 跨平台版**,详见 [AVALONIA.md](AVALONIA.md)。
Windows 和 Linux 都编译 `src/SopHelper.Avalonia`;之前的 `SopHelper.Linux` 简化验证版不再作为部署入口。
Windows 和 Linux 都编译 `src/SopHelper.Avalonia`;旧 Linux 简化验证版已删除。
## 本地生成 Linux 包
```powershell
dotnet publish src/SopHelper.Avalonia -c Release -r linux-x64 --self-contained true -o artifacts/avalonia/linux-x64
dotnet publish src/SopHelper.Avalonia -c Release -r linux-x64 -p:NativePlatform=Linux --self-contained true -o artifacts/avalonia/linux-x64
```
在目标机的图形会话中执行 `./SopHelper.Avalonia`。训练功能需要为 Linux 单独安装 Python 运行时:

236
README.md
View File

@ -1,211 +1,63 @@
# SopHelper — 单相机 SOP 辅助
# SopHelper.Avalonia
工位上接一个 UVC 或海康工业相机,程序按 YAML 配方定义的步骤顺序判定操作员动作:逐步打勾、
超时报违规、留日志和快照。侧栏的「零件标注与训练」集成 PartTrainer 的采集、标注与模型训练流程。
Windows / Linux 共用一套 Avalonia 桌面程序,保留 SOP 作业辅助、配方编辑、相机采集、YOLO 与双手关键点检测,以及零件标注和训练流程。
引擎逻辑移植自 [VisionInspectionSystem](https://github.com/TheDoorIsUnlocked/VisionInspectionSystem)(MIT)。
本目录是唯一活动仓库。原 WPF 仓库完整归档至 `../archive/SopHelper-WPF-20261108/`;旧 Linux 简化版已从活动代码中删除。
Git 提交历史保留。当前代码、构建和测试不依赖归档目录。
## 结构
## 目录
```
SopHelper.Engine net8.0 纯类库,零 UI 依赖(可单测、可被别的项目引用)
Camera/ UVC(MSMF / DSHOW)及海康 MVS(GigE / USB)连续采集,单相机
Inference/ YOLOv8 ONNX(自带 letterbox + DFL 解码 + NMS)
MediaPipe 手部两阶段(palm 192 → 方形裁剪 → landmark 224)
Pipeline/ 采集 → 推理 → 结果帧,支持抽帧
Sop/ 配方加载 + 条件判定 + 违规 + 状态机
SopHelper.App net8.0-windows,Prism.DryIoc
纯 WPF 样式,无 HandyControl / SkiaSharp.Views.WPF
```text
SopHelper.Avalonia.slnx
src/
SopHelper.Avalonia/ 统一桌面界面、ViewModel、平台适配
SopHelper.CrossPlatform.Engine/ 独立共享引擎:相机、推理、SOP、录像、训练数据
configs/sop/ YAML 配方
models/、yolo_models/ 模型
libs/ Windows/Linux 海康绑定及可选 CUDA 库
tools/ worker、运行环境、发布和部署脚本
tests/ Avalonia、引擎和硬件回归检查
python/ 本地 Python 运行环境(不入 Git)
workspace/ 设置、录像和工作数据(不入 Git)
artifacts/ 构建和测试输出(不入 Git)
```
依赖包括 Prism.DryIoc、OpenCvSharp4、Microsoft.ML.OnnxRuntime.Gpu、YamlDotNet 和海康 MVS SDK —— 没有
GPL/AGPL 组件(YOLO 那段是自己写的,就是为了不引 GPL-3.0 的 YoloDotNet)。
## 跑起来
```bash
dotnet build SopHelper.slnx
```
1. 把模型丢进 `models/` 和 `yolo_models/`。构建时自动拷到输出目录,模型文件本身不入 git。
当前用的三份(获取渠道与许可证):
| 模型 | 来源 | 许可证 |
|---|---|---|
| `palm_detection_full_Nx3x192x192_post.onnx` | PINTO0309/hand_landmark release 1.0.0 | Apache-2.0 |
| `hand_landmark_sparse_Nx3x224x224.onnx` | 同上 | Apache-2.0 |
| `yolo11n.onnx` | dme-compunet/YoloSharp 仓内 | **AGPL-3.0**(Ultralytics 血统),仅测试用,生产前换掉 |
2. 接相机。
3. 界面上:刷新相机 → 选配方 → 应用 → 开始/停止。
没有模型也能起:缺哪个就在日志里报哪条警告,只有手部类和计时类条件能工作。
运行时,检测到的手会直接标在视频画面上:21 个关键点与骨架连线,不显示手部外框或文字标签。
标记与 ROI 共用原图坐标,随预览一起缩放;未检测到手或停止采集时清除。
需要 `models/` 中的 palm 与 landmark 两份模型,缺失时日志会提示。
手掌检测与手部关键点确认的默认置信度门槛均为 40%(界面上的置信度滑块用于 YOLO 目标检测)。
默认支持同帧显示两只手。针对 palm 导出中内置的单手 NMS 限制,加载时仅在内存中
适配候选输出数量,原始模型文件不变;相邻手部去重使用原始手掌框。
双手回归检查(提供一段同时包含左右手的视频,从项目根目录运行):
```bash
dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4
```
### GPU 推理
使用 ONNX Runtime GPU 1.23.0,手掌、手部关键点与 YOLO 默认优先使用 NVIDIA CUDA,
不可用时自动回退 CPU。加载配方后,日志会显示手部与 YOLO 的实际推理后端,以及 GPU 回退原因。
图像裁剪、预处理及画面绘制仍在 CPU 上执行。
现场需安装 NVIDIA 驱动、兼容的 CUDA 12.x 运行库(本机为 CUDA 12.6),并确保 CUDA `bin`
在进程 PATH 中;还需要 cuDNN 9。可从项目目录执行以下脚本,从 NVIDIA 官方下载 cuDNN,
校验 SHA256 后将 DLL 及许可证放入 `libs/cuda/`:
## 构建和运行
```powershell
pwsh -NoProfile -File tools/Install-GpuRuntime.ps1
dotnet build SopHelper.slnx
dotnet build SopHelper.Avalonia.slnx -c Release
dotnet run --project src/SopHelper.Avalonia
pwsh -File tools/Publish-Avalonia.ps1
```
`libs/cuda/` 不入 Git,构建/发布时自动携带其中的 DLL 和许可证。换机器部署时也需提供 CUDA 12.x
运行库。脚本不修改系统安装和 PATH。兼容要求见 [ONNX Runtime CUDA 文档](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html)。
发布结果:`artifacts/avalonia/win-x64/SopHelper.Avalonia.exe` 和
`artifacts/avalonia/linux-x64/SopHelper.Avalonia`。
两个平台使用同一套视图、ViewModel 和业务代码,仅供应商 SDK 绑定及原生运行库不同。
强制验证 GPU(若回退 CPU 则测试失败);对比 CPU 可将 `--require-gpu` 换成 `--cpu`:
Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部署见 [LINUX.md](LINUX.md)。
发布脚本会携带 Windows 的仓库 Python 运行时,Linux 需建立对应平台环境。
```bash
dotnet run --project tests/HandDetectionSmoke/HandDetectionSmoke.csproj -- path/to/two-hands.mp4 --require-gpu
```
## 操作流程
### 海康相机取视频
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
2. 配方编辑器保留步骤、区域、全局设置、检测模型四个标签页;区域坐标使用原图像素。
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。
4. 模型、相机和 Python 依赖的实际状态以日志和诊断结果为准。
参考 `plcsharp` 的 `MvCameraControl` 接法,支持海康机器人 GigE / USB 工业相机。
`libs/MvCameraControl.Net.dll` 随项目提供,构建和发布会自动复制;现场需安装
**MVS 4.5 或以上的 x64 运行时**(与 SDK 兼容),使用 x64 进程运行。
原生运行时通常位于 `C:\Program Files (x86)\Common Files\MVS\Runtime\Win64_x64`。
模型文件:`palm_detection_full_Nx3x192x192_post.onnx`、`hand_landmark_sparse_Nx3x224x224.onnx`;
目标检测模型由配方选择。测试用 `yolo11n.onnx` 和训练依赖沿用其上游许可。
1. 先在 MVS 中确认能发现相机并正常取图,然后关闭 MVS 对该设备的连接。
2. GigE 相机与网卡配置在可互通的网段;USB 相机安装 MVS USB 驱动。
3. SOP 页点击「刷新」,选择 `海康 型号 / 序列号`,选择配方后点击「开始/停止」。
视频进入现有预览、ROI、推理和 SOP 判定流程。
4. 停止后可切换相机,再次开始会重新连接;运行及连接过程中禁止切换设备。
采集会设置连续模式并关闭触发;GigE 尝试优化包大小。输出统一为 BGR 三通道,
灰度、Bayer、RGB、YUV 等格式转换后再交给管线。SDK 缓冲在复制后立即归还。
未安装 MVS 时日志提示原因,UVC 仍可使用。此功能针对工业相机,不包含安防摄像头 RTSP。
应用退出统一释放相机,再释放推理管线,不依赖页面的 `Destroy()`。
退出时等待尚未完成的设备操作及采集线程,归还缓冲、关闭设备并反初始化 MVS。
退出回归检查(不创建窗口,执行正式 WPF 退出链路):
```bash
dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj
# 连接现场海康、收到视频帧后直接退出,并在同一进程中验证设备可重新打开
dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -- --hardware
```
## 零件标注与训练
侧栏「零件标注与训练」包含以下工作流:相机录像、导入视频与抽帧、手工画框、SAM2 双向传播、逐帧或一键复核、负样本与排除帧、YOLO 数据集导出、训练与 ONNX 导出,以及可选视觉 API 建议框。切换到 SOP 页再返回会保留当前项目及任务。
首次使用 Python 功能,在 SopHelper 根目录执行:
## 验证
```powershell
powershell -ExecutionPolicy Bypass -File tools/Setup-Python.ps1 -Sam2
# CPU 环境附加 -Cpu
dotnet run --project tests/Avalonia.Smoke -c Release
dotnet run --project tests/HandednessSmoke -c Release
dotnet run --project tests/Training.Smoke -c Release -- python/python.exe
dotnet run --project tests/YoloModelSmoke -c Release -- models/yolo11n.onnx
# 现场相机检查会实际打开设备;先关闭其他程序对相机的连接。
dotnet run --project tests/Mvs.Smoke -c Release -- --hardware
```
程序固定使用可执行文件同目录的 `python/python.exe`,不读取系统 PATH 或设置文件中的 Python 路径,界面不提供路径设置。安装脚本将完整运行时及依赖放在仓库 `python/`,构建和发布会携带该目录。相机预览和录像不需要 Python。设置保存在 `workspace/settings.json`,录像默认保存在 `workspace/recordings`;API Key 不保存到配置或日志。原 PartTrainer 的 `project.json` 可直接打开,项目中原有的绝对视频、权重路径需要仍然有效。集成后的源码、Python worker 和安装脚本均在本仓库内,构建与发布无需 PartTrainer 目录。
相机录像窗口以模态打开;SOP 正在运行或操作相机时会提示先停止,避免两个流程同时占用设备。关闭采集窗口会结束并封装录像。关闭主窗口时会取消后台 Python 任务、等待进程退出并释放相机;即使已切回 SOP 页面也会清理。
标注目前支持单目标、单类别矩形框。导出只包含已复核正样本和明确标记的无目标帧,按时间划分训练与验证并保留间隔。单段视频的指标用于验证流程,实际效果需使用独立现场视频评估。
训练后点击「导出最新模型为 ONNX」,在 SOP 配方编辑器「检测模型」选择导出的 ONNX;类别表可留空以读取模型元数据,也可提供对应类别表。导出采用固定尺寸、opset 17、无内置 NMS。原 PartTrainer 项目保留,可继续独立运行。
Python 依赖中的 Ultralytics 使用 AGPL-3.0 / 商业许可;SAM2 使用其上游许可。部署时需遵守所选依赖与模型的许可。
集成回归检查:
```powershell
dotnet run --project tests/Training.Smoke
dotnet run --project tests/Training.UiSmoke
dotnet run --project tests/Training.CameraSmoke
dotnet run --project tests/Training.ShellSmoke
python/python.exe -X utf8 -m unittest discover -s tests -p test_worker.py -v
```
## 配方
`configs/sop/*.yaml`,写好的例子见 `configs/sop/demo.yaml`。
支持的方法(就是参考项目现有配方里真正被用过的那些):
| method | 需要模型 | 依赖 |
|---|---|---|
| `time_elapsed` | 否 | 计时 |
| `hand_in_region` | 否 | MediaPipe |
| `hand_move` | 否 | MediaPipe(起点证据来自上一帧的轨迹) |
| `object_present` | 是 | YOLO |
| `object_in_zone` | 是 | YOLO |
| `hand_near_object` | 是 | YOLO + MediaPipe |
| `person_present` | 是 | YOLO(COCO 的 person) |
步骤里写了没实现的方法,**加载配方时就会报出来**——否则现场表现是"这一步永远不推进",
极难定位。
违规:`timeout` / `object_removed`,同类 3 秒冷却。
### 配方编辑器
SOP 页配方行的「编辑 / 新建」。表单式,四个 tab:步骤 / 区域 / 全局设置 / 检测模型,
字段与 YAML 一一对应;method、区域名、hand、违规类型都是下拉选——就是为了不让
"照抄别人的 YAML 拼错一个字母"这种事发生(下拉候选就是 `ConditionMethod` 那几项)。
区域改键名会同步更新所有引用它的步骤;删区域会清掉引用。
“检测模型”页选择普通 YOLO 的 ONNX 文件和对应类别表;类别表留空时可从模型的 `names` 元数据读取。
加载时会检查类别数量和输出格式,加载失败会在 SOP 日志提示,切换到缺失模型也会释放旧模型。
该页的“相机曝光(μs)”随配方保存到 `sop.settings.exposure_time_us`,例如 10000 表示 10 毫秒。
海康相机在区域取图与 SOP 启动前关闭自动曝光并应用该值;留空保留设备设置。UVC 暂不支持微秒曝光设置,请留空。
程序启动时自动扫描相机并恢复上次成功使用的设备,主窗口默认最大化。
区域页支持图像画框标定:
1. 停止运行,在 SOP 页选好相机,打开「编辑 / 新建」→「区域」。
2. 已有预览画面会作为背景带入;也可点「从相机取图」获取新的一帧,或「打开图片」载入原图。
取图完成后自动关闭相机,不启动 SOP 判定。
3. 左侧选中区域(没有则点「加区域」),在图上按住左键拖动画框,松开后更新 X1/Y1/X2/Y2。
支持反方向拖动;超出图像边界会截取到边界;Esc 取消本次绘制。
4. 重画可直接替换所选区域;下方数字可微调,并同步更新图上的框。点击「保存」写入配方。
图像保持原比例显示,坐标保存为原图像素,不包含预览留白。打开的图片应与现场相机分辨率一致。
区域编辑回归检查(可加 `--hardware` 使用现场海康取图):
```bash
dotnet run --project tests/RegionEditorSmoke/RegionEditorSmoke.csproj
```
两条要注意的:
- **保存是重写整个文件,注释会丢**(YamlDotNet 不保留注释)。`demo.yaml` 顶上那些说明
注释,编辑器保存一次就没了——那些话是给编辑器的字段说的,不是给自己的。
- **运行中不能编辑**,和「应用」一致,得先停止。保存成功后界面会重扫 `configs/sop`、
选中刚存的配方并立即重新应用,区域覆盖层跟着更新。新建时文件名可填,之后不可改
(SOP 页是按文件名选配方的)。
## 判定语义(踩过的坑)
- **稳定帧门控**:按 `(步骤Id, 条件序号)` 累计连续命中帧数,达标才放行,未命中立即清零。
`time_elapsed` / `hand_move` 豁免(自带时序或瞬时语义)。
- **Start / Reset 必须清空跨帧状态**,否则第二轮会"秒过",防抖形同虚设。
- **区域坐标是绝对像素**,必须在真机画面上标定,别照抄别人的 YAML。
## 已知限制
- 单相机。多相机需求请先改 `ICameraService` 的契约再说。
- YOLO 和 MediaPipe 的解析是照搬参考项目逻辑重写的,本机没有 onnx 文件,
**只过了编译,没跑过真实推理**。第一次接上模型时先拿一段已知动作的视频验一遍。
- 快照只存帧(`snaps/`),不叠加 ROI 和检测框。
运行 `--check-runtime` 可检查发布包的模型和 SOP 引擎。
Avalonia 验证使用假相机,覆盖导航、原始配方字段保持、标注保存、相机缓冲显示和画框坐标。
详细架构与平台验证记录见 [AVALONIA.md](AVALONIA.md),研发方向见 [研发计划.md](研发计划.md)。

View File

@ -1,6 +0,0 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/SopHelper.Linux.Engine/SopHelper.Linux.Engine.csproj" />
<Project Path="src/SopHelper.Linux/SopHelper.Linux.csproj" />
</Folder>
</Solution>

View File

@ -1,6 +0,0 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/SopHelper.App/SopHelper.App.csproj" />
<Project Path="src/SopHelper.Engine/SopHelper.Engine.csproj" />
</Folder>
</Solution>

View File

@ -1,12 +0,0 @@
<prism:PrismApplication x:Class="SopHelper.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/">
<prism:PrismApplication.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</prism:PrismApplication.Resources>
</prism:PrismApplication>

View File

@ -1,167 +0,0 @@
using System.IO;
using System.Reflection;
using System.Windows;
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.RecipeEditor;
using SopHelper.VVMs.SopPage;
using SopHelper.VVMs.MainWindow;
namespace SopHelper;
/// <summary>
/// 应用程序入口,负责初始化 Prism 框架和注册组件(启动链照搬 plcsharp)
/// </summary>
public partial class App
{
private ICameraService? _camera;
private DetectionPipeline? _pipeline;
private Engine.Training.WorkerClient? _trainingWorker;
/// <summary>
/// 注册应用程序所需的类型和服务
/// </summary>
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
RegisterEvents(); // 捕获全局异常
// 注册带 [Model] 特性的类,单例
foreach (var model in from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetCustomAttribute<ModelAttribute>() is not null
select t)
{
_ = containerRegistry.RegisterSingleton(model);
}
// 注册带 [NavigationPage] 特性的 View 到导航
foreach (var view in from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetCustomAttribute<NavigationPageAttribute>() is not null
select t)
{
containerRegistry.RegisterForNavigation(view, view.Name);
}
_ = containerRegistry.RegisterSingleton<NavigationModel>();
// 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集,
// 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。
// 共享硬件和推理由应用持有;页面销毁和容器回收不能代替应用退出清理。
_camera = new CameraService();
_pipeline = new DetectionPipeline(_camera);
containerRegistry.RegisterInstance<ICameraService>(_camera);
containerRegistry.RegisterInstance(_pipeline);
_ = containerRegistry.RegisterSingleton<SopEngine>();
// ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册
_ = containerRegistry.RegisterSingleton<SopPageViewModel>();
_trainingWorker = new Engine.Training.WorkerClient();
containerRegistry.RegisterInstance(_trainingWorker);
containerRegistry.RegisterSingleton<Training.MainViewModel>();
// 配方编辑器弹窗(SOP 页「编辑」「新建」按钮弹出)
containerRegistry.RegisterDialog<RecipeEditor, RecipeEditorViewModel>("RecipeEditorDialog");
}
/// <summary>
/// 创建Shell
/// </summary>
protected override Window CreateShell()
{
var navigate = Container.Resolve<NavigationModel>();
// 反射收集导航页
foreach (var view in from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetCustomAttribute<NavigationPageAttribute>() is not null
orderby t.GetCustomAttribute<NavigationPageAttribute>()!.Index
select t)
{
var page = view.GetCustomAttribute<NavigationPageAttribute>()!;
var item = Container.Resolve<NavigateItem>();
item.ViewName = page.ViewName;
item.DisplayName = page.DisplayName;
navigate.Pages.Add(item);
}
var window = Container.Resolve<MainWindow>();
// 默认页:区域要等窗口加载后才注册,CreateShell 里立刻 RequestNavigate 会静默失败
//(实测启动后内容区是空的),必须等 Loaded;走 SelectedIndex 让侧栏同步高亮。
window.Loaded += (_, _) =>
{
if (navigate.Pages.Count > 0) navigate.SelectedIndex = 0;
};
return window;
}
protected override void OnExit(ExitEventArgs e)
{
try
{
_trainingWorker?.Dispose();
// Dispose 等待采集线程退出、归还缓冲并关闭设备,然后才能释放推理模型。
try { _camera?.Dispose(); }
catch (Exception ex) { Log(ex, "Exit.Camera"); }
try { _pipeline?.Dispose(); }
catch (Exception ex) { Log(ex, "Exit.Pipeline"); }
}
finally
{
base.OnExit(e);
}
}
/// <summary>
/// 自动寻找ViewModel并绑定到View,要求ViewModel命名为View的全名加上ViewModel,比如MainWindow的ViewModel命名为MainWindowViewModel
/// </summary>
protected override void ConfigureViewModelLocator()
{
base.ConfigureViewModelLocator();
ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
{
var viewName = viewType.FullName;
var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
var viewModelName = $"{viewName}ViewModel, {viewAssemblyName}";
return Type.GetType(viewModelName);
});
}
/// <summary>
/// 捕获全局异常
/// </summary>
private static void RegisterEvents()
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
Log(e.ExceptionObject as Exception, "AppDomain");
Current.DispatcherUnhandledException += (_, e) =>
{
Log(e.Exception, "Dispatcher");
e.Handled = true; // 上位机不能因一次异常退出
};
}
private static void Log(Exception? ex, string from)
{
if (ex is null) return;
var line = $"[{DateTime.Now:HH:mm:ss.fff}] [{from}] {ex.Message}";
Console.WriteLine(line);
try
{
Directory.CreateDirectory("logs");
File.AppendAllText(Path.Combine("logs", "error.log"), line + Environment.NewLine);
}
catch
{
// 日志失败不影响主流程
}
}
}

View File

@ -1,167 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<!-- Vector drawing generated from bws.svg; preserve the SVG as the source asset. -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DrawingImage x:Key="BellwetherLogo">
<DrawingImage.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="Transparent" Geometry="M0,0 H380 V120 H0 Z" />
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.08,0,0,1.08,-40.6,-75.6892" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#2B387C" Geometry="F0 M58.0 108.0C63.12 107.93 68.25 107.87 73.37 107.84C75.11 107.82 76.85 107.8 78.59 107.77C81.1 107.74 83.61 107.72 86.12 107.71C86.51 107.7 86.51 107.7 88.45 107.66C93.94 107.66 97.99000000000001 108.74 103.0 111.0C105.0 113.0 105.0 113.0 105.44 116.81C105.35 120.28 105.03999999999999 120.95 102.81 123.88C100.22 125.84 98.09 127.03 95.0 128.0C95.83 128.52 96.65 129.03 97.5 129.56C100.0 132.0 100.0 132.0 100.62 135.44C99.82 140.01 98.69 141.21 95.0 144.0C87.73 147.84 81.72 149.15 73.52 149.1C72.7 149.1 71.88 149.09 71.03999999999999 149.09C68.45 149.09 65.85 149.07999999999998 63.25 149.06C61.49 149.06 59.72 149.05 57.96 149.05C53.64 149.04 49.32 149.02 45.0 149.0C47.31 139.96 50.21 131.15 53.19 122.31C53.66 120.92 54.12 119.52 54.59 118.13C55.72 114.75 56.86 111.37 58.0 108.0ZM63.0 130.0C65.75 129.92 68.5 129.86 71.25 129.81C72.03 129.79 72.8 129.76 73.61 129.74C79.43 129.66 79.43 129.66 82.55 131.51C83.03 132.0 83.51 132.49 84.0 133.0C83.83 137.35 83.5 139.45 80.53 142.72C76.49 145.88 72.55 145.57 67.62 145.31C66.79 145.29 65.96 145.27 65.11 145.24C63.07 145.19 61.03 145.1 59.0 145.0C59.48 143.06 59.96 141.12 60.44 139.19C60.7 138.11 60.97 137.03 61.25 135.92C61.76 133.93 62.35 131.95 63.0 130.0ZM69.0 111.0C71.4 110.92 73.79 110.86 76.19 110.81C76.86 110.79 77.53 110.76 78.23 110.74C82.71000000000001 110.67 85.4 111.31 89.0 114.0C90.0 115.0 90.0 115.0 90.38 117.25C89.84 121.16 87.96000000000001 122.52 85.0 125.0C82.28999999999999 125.9 80.76 126.12 77.99 126.1C77.61 126.1 77.61 126.1 75.69 126.09C74.91 126.08 74.12 126.07 73.31 126.06C72.52 126.06 71.72 126.05 70.9 126.05C68.93 126.03999999999999 66.97 126.02 65.0 126.0C65.56 122.23 66.31 118.73 67.56 115.12C67.83 114.34 68.1 113.56 68.38 112.76C68.58 112.18 68.79 111.6 69.0 111.0Z" />
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,108.0,108.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#253278" Geometry="F1 M0 0 C4.29 0 8.58 0 13 0 C12.67 6.6 12.34 13.2 12 20 C13.4 17.53 14.81 15.05 16.25 12.5 C20.61 5.42 20.61 5.42 25.34 4 C28.62 4.06 28.62 4.06 34 5 C34.16 7.64 34.16 7.64 35 21 C35.27 20.45 35.27 20.45 36.64 17.68 C37.37 16.22 38.09 14.77 38.81 13.31 C39.17 12.59 39.53 11.87 39.89 11.13 C40.59 9.72 41.31 8.31 42.03 6.91 C42.85 5.29 43.62 3.65 44.38 2 C46 0 46 0 48.92 -0.49 C50 -0.43 51.08 -0.37 52.19 -0.31 C53.27 -0.27 54.36 -0.22 55.48 -0.18 C56.31 -0.12 57.14 -0.06 58 0 C53.27 10.09 48.48 20.15 43.5 30.12 C43.07 31 42.63 31.87 42.19 32.76 C41.79 33.57 41.38 34.37 40.97 35.2 C40.61 35.91 40.26 36.62 39.89 37.35 C39 39 39 39 38 40 C35.98 40.07 33.96 40.08 31.94 40.06 C31.39 40.06 31.39 40.06 28.59 40.04 C27.74 40.02 26.88 40.01 26 40 C25.94 39.4 25.89 38.8 25.83 38.18 C25.58 35.47 25.32 32.77 25.06 30.06 C24.98 29.12 24.89 28.17 24.8 27.2 C24.71 26.3 24.62 25.4 24.54 24.47 C24.46 23.64 24.38 22.81 24.3 21.95 C24 20 24 20 23 19 C20.85 22.29 18.71 25.58 16.56 28.88 C16.26 29.34 16.26 29.34 14.71 31.71 C14.13 32.61 13.54 33.51 12.94 34.43 C12.4 35.26 11.86 36.08 11.31 36.94 C10 39 10 39 9 41 C4.71 41 0.42 41 -4 41 C-3.37 30.27 -2.32 19.67 -1 9 C-0.66 6 -0.33 3 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,175.75,77.5625" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D13A2E" Geometry="F1 M0 0 C0.48 -0.01 0.48 -0.01 2.9 -0.07 C10.94 -0.04 17.42 1.99 24.19 6.31 C28.61 10.87 29.42 14.58 29.44 20.81 C29.39 22.69 29.33 24.56 29.25 26.44 C25.62 26.44 21.99 26.44 18.25 26.44 C17.86 25.36 17.47 24.29 17.06 23.19 C15.45 19.49 13.78 17.56 10.25 15.44 C-8.16 8.49 -29.61 16.24 -46.75 23.44 C-47.19 23.71 -47.19 23.71 -49.43 25.11 C-54.58 27.17 -59.64 26.75 -65.12 26.62 C-65.68 26.62 -65.68 26.62 -68.51 26.58 C-71.26 26.55 -74 26.5 -76.75 26.44 C-73.33 22.84 -69.82 20.7 -65.38 18.56 C-64.67 18.22 -63.96 17.87 -63.22 17.51 C-61.07 16.48 -58.91 15.45 -56.75 14.44 C-55.57 13.88 -54.4 13.33 -53.18 12.76 C-44.91 9.05 -36.51 6.3 -27.75 3.97 C-25.95 3.49 -24.16 2.98 -22.37 2.46 C-14.9 0.54 -7.69 0.11 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,185.390625,107.90234375" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#263378" Geometry="F1 M0 0 C0.35 0 0.35 0 2.14 0 C4.38 0.01 6.62 0.02 8.86 0.04 C10.38 0.04 11.91 0.04 13.43 0.05 C17.16 0.06 20.88 0.08 24.61 0.1 C23.62 3.07 22.63 6.04 21.61 9.1 C20.77 9.12 19.93 9.14 19.07 9.16 C15.97 9.24 12.86 9.32 9.76 9.42 C7.75 9.47 5.74 9.52 3.74 9.57 C3.11 9.59 3.11 9.59 -0.07 9.68 C-1.23 9.72 -2.4 9.75 -3.59 9.78 C-6.39 10.1 -6.39 10.1 -8.39 12.1 C-8.39 13.09 -8.39 14.08 -8.39 15.1 C-7.16 15.14 -5.93 15.17 -4.66 15.21 C-3.03 15.28 -1.4 15.34 0.23 15.41 C1.04 15.43 1.85 15.46 2.68 15.48 C7.67 15.7 11.29 16.34 15.61 19.1 C17.22 22.32 17.07 25.6 16.61 29.1 C14.1 34.21 10.45 37.28 5.61 40.1 C1.91 41.33 -1.49 41.22 -5.34 41.2 C-6.11 41.19 -6.89 41.19 -7.68 41.19 C-10.15 41.19 -12.61 41.17 -15.08 41.16 C-16.75 41.16 -18.42 41.15 -20.1 41.15 C-24.19 41.14 -28.29 41.12 -32.39 41.1 C-31.4 38.13 -30.41 35.16 -29.39 32.1 C-28.46 32.08 -27.53 32.06 -26.58 32.04 C-23.14 31.96 -19.7 31.87 -16.26 31.78 C-14.77 31.74 -13.28 31.71 -11.79 31.68 C-9.65 31.63 -7.51 31.57 -5.37 31.51 C-4.08 31.48 -2.79 31.45 -1.46 31.42 C1.61 31.1 1.61 31.1 3.61 29.1 C3.61 28.11 3.61 27.12 3.61 26.1 C3.29 26.09 3.29 26.09 1.67 26.07 C-1.25 26.02 -4.16 25.93 -7.08 25.85 C-8.09 25.83 -9.09 25.82 -10.13 25.8 C-14.59 25.66 -17.62 25.53 -21.56 23.32 C-24.16 20.16 -24.05 18.29 -23.8 14.34 C-23 9.97 -20.99 7.31 -17.48 4.66 C-11.48 0.72 -7.23 -0.03 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,55.0,153.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D13A2D" Geometry="F1 M0 0 C2.42 -0.16 4.83 -0.28 7.25 -0.38 C7.93 -0.43 8.61 -0.48 9.32 -0.53 C11.33 -0.59 11.33 -0.59 15 0 C17.24 2.84 17.24 2.84 19 6 C26.15 12.65 36.47 11.67 45.56 11.36 C52.28 11 58.53 9.85 65 8 C65.87 7.77 66.75 7.54 67.65 7.31 C72.34 6.01 76.68 4.29 81.12 2.31 C86.1 0.17 89.63 -0.52 95 0 C92.77 2.5 90.79 3.71 87.68 4.94 C86.84 5.28 85.99 5.61 85.12 5.96 C84.23 6.3 83.35 6.65 82.44 7 C81.58 7.34 80.72 7.69 79.84 8.04 C59.97 15.87 34.34 23.1 13.27 16.04 C7.96 13.6 4.12 10.78 1 5.81 C0 3 0 3 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,150.0,153.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D34338" Geometry="F1 M0 0 C-3.24 3.54 -6.88 4.94 -11.25 6.75 C-11.99 7.08 -12.73 7.41 -13.49 7.75 C-18.5 9.84 -21.69 10.26 -27 9 C-23.59 6.13 -19.84 4.47 -15.75 2.81 C-15.43 2.68 -15.43 2.68 -13.84 1.99 C-9.04 0.04 -5.17 -0.26 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,88.0,165.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D86359" Geometry="F1 M0 0 C2.75 -0.11 5.5 -0.19 8.25 -0.25 C9.03 -0.28 9.8 -0.32 10.61 -0.35 C16.43 -0.45 16.43 -0.45 19.55 2.02 C20.03 2.67 20.51 3.33 21 4 C20.17 3.84 20.17 3.84 16 3 C16 2.34 16 1.68 16 1 C10.72 1 5.44 1 0 1 C0 0.67 0 0.34 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,131.0,159.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D0392D" Geometry="F1 M0 0 C-0.33 1.32 -0.66 2.64 -1 4 C-3.31 3.67 -5.62 3.34 -8 3 C-4.94 0.38 -4.27 0 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,150.0,153.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D04337" Geometry="F1 M0 0 C-2.23 2.5 -4.21 3.71 -7.32 4.94 C-7.74 5.11 -7.74 5.11 -9.88 5.96 C-10.77 6.3 -11.65 6.65 -12.56 7 C-13.42 7.34 -14.28 7.69 -15.16 8.04 C-21.02 10.35 -26.94 12.28 -33 14 C-33.73 14.22 -34.46 14.44 -35.21 14.66 C-39.15 15.77 -42.06 16.23 -46 15 C-46 14.34 -46 13.68 -46 13 C-51.28 13 -56.56 13 -62 13 C-62 12.67 -62 12.34 -62 12 C-61.43 11.98 -61.43 11.98 -58.55 11.89 C-48.71 11.49 -39.56 10.51 -30 8 C-29.12 7.77 -28.24 7.55 -27.34 7.31 C-22.65 6 -18.32 4.28 -13.88 2.31 C-8.9 0.17 -5.37 -0.52 0 0 Z " />
</DrawingGroup>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="0.2226833,0,0,-0.2070485,195.76487,60.23789" />
</DrawingGroup.Transform>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,0.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M201 178Q201 83 202 55L187 48V184H78V48L63 42Q64 80 64.0 119.5Q64 159 63 198L79 190H186L196 200L211 185ZM28 -19Q88 6 102.5 28.5Q117 51 120.0 83.5Q123 116 122 164L147 152L138 145Q138 70 121.5 35.0Q105 0 29 -23ZM147 43Q190 27 208.0 14.0Q226 1 223.0 -9.5Q220 -20 216 -20Q214 -20 210 -15Q201 -3 187.0 10.0Q173 23 146 39Z">
<GeometryDrawing.Pen>
<Pen Brush="#FFFFFF" LineJoin="Round" Thickness="5" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,256.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M244 -4V-8Q227 -8 219 -19Q176 27 165 109H158Q153 53 130.0 23.5Q107 -6 63 -23L62 -20Q101 3 120.0 31.0Q139 59 144 109H115Q102 109 91 106L82 115H144Q146 146 146 176Q115 174 91 172V176Q114 179 133.0 182.0Q152 185 173.5 190.5Q195 196 207 203L224 186Q205 185 160 178Q160 147 158 115H208L224 130L243 109H170Q195 12 244 -4ZM86 161Q57 56 54.5 43.5Q52 31 52 13Q52 -5 51.5 -10.5Q51 -16 48 -16Q45 -16 38.5 -12.5Q32 -9 32 -2Q32 5 34 11Q37 20 37 26Q37 32 33.0 36.0Q29 40 14 45V49Q29 47 34.5 47.0Q40 47 46.0 58.0Q52 69 82 162ZM14 138Q45 123 44.5 113.5Q44 104 41.0 100.5Q38 97 36 97Q33 97 30 106Q26 118 12 136ZM36 200Q58 190 61.5 185.5Q65 181 65 177Q65 172 62.0 166.5Q59 161 57 161Q54 161 52 169Q47 182 34 198Z">
<GeometryDrawing.Pen>
<Pen Brush="#FFFFFF" LineJoin="Round" Thickness="5" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,512.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M76 66 99 56 91 49V13Q90 -3 103 -1H169Q181 0 182.5 13.0Q184 26 185 45H190Q191 23 193.5 13.5Q196 4 204 2Q196 -16 167 -14H98Q76 -16 77 6Q77 49 76 66ZM106 76 108 79Q126 72 135.0 66.0Q144 60 145.0 53.5Q146 47 142.5 41.5Q139 36 137 36Q134 36 131 44Q126 56 106 76ZM197 54 199 57Q219 47 229.0 39.0Q239 31 239.0 23.0Q239 15 235.0 10.5Q231 6 230 6Q226 6 222 18Q216 34 197 54ZM46 59H50Q50 34 48.0 22.0Q46 10 40.5 6.5Q35 3 30 3Q26 3 22.5 4.5Q19 6 19 7Q19 11 27 19Q39 31 46 59ZM67 188V143H122V188ZM136 188V143H190V188ZM67 137V93H122V137ZM136 137V93H190V137ZM204 185V118Q204 98 205 80L190 74V87H67V77L52 71Q53 101 53.0 142.5Q53 184 52 203L67 194H188L195 204L212 192Z">
<GeometryDrawing.Pen>
<Pen Brush="#FFFFFF" LineJoin="Round" Thickness="5" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="0.0123755,0,0,-0.0129604,196.14367,101.0" />
</DrawingGroup.Transform>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,0.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M150 1466H736Q910 1466 995.5 1451.5Q1081 1437 1148.5 1391.0Q1216 1345 1261.0 1268.5Q1306 1192 1306 1097Q1306 994 1250.5 908.0Q1195 822 1100 779Q1234 740 1306.0 646.0Q1378 552 1378 425Q1378 325 1331.5 230.5Q1285 136 1204.5 79.5Q1124 23 1006 10Q932 2 649 0H150ZM446 1222V883H640Q813 883 855 888Q931 897 974.5 940.5Q1018 984 1018 1055Q1018 1123 980.5 1165.5Q943 1208 869 1217Q825 1222 616 1222ZM446 639V247H720Q880 247 923 256Q989 268 1030.5 314.5Q1072 361 1072 439Q1072 505 1040.0 551.0Q1008 597 947.5 618.0Q887 639 685 639Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,1479.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M149 0V1466H1236V1218H445V893H1181V646H445V247H1264V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,2845.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M157 0V1454H453V247H1189V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,4096.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M157 0V1454H453V247H1189V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,5347.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M357 0 7 1466H310L531 459L799 1466H1151L1408 442L1633 1466H1931L1575 0H1261L969 1096L678 0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,7280.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M149 0V1466H1236V1218H445V893H1181V646H445V247H1264V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,8646.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M479 0V1218H44V1466H1209V1218H775V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,9897.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M150 0V1466H446V889H1026V1466H1322V0H1026V641H446V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,11376.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M149 0V1466H1236V1218H445V893H1181V646H445V247H1264V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,12742.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M150 0V1466H773Q1008 1466 1114.5 1426.5Q1221 1387 1285.0 1286.0Q1349 1185 1349 1055Q1349 890 1252.0 782.5Q1155 675 962 647Q1058 591 1120.5 524.0Q1183 457 1289 286L1468 0H1114L900 319Q786 490 744.0 534.5Q702 579 655.0 595.5Q608 612 506 612H446V0ZM446 846H665Q878 846 931.0 864.0Q984 882 1014.0 926.0Q1044 970 1044 1036Q1044 1110 1004.5 1155.5Q965 1201 893 1213Q857 1218 677 1218H446Z" />
</DrawingGroup>
</DrawingGroup>
</DrawingGroup>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</ResourceDictionary>

View File

@ -1,39 +0,0 @@
namespace SopHelper.Core.Prism;
/// <summary>
/// 标志此特性的类会被注册为单例(照搬 plcsharp 约定)
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class ModelAttribute : Attribute
{
}
/// <summary>
/// 标志此特性的 View 会被注册到导航列表
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class NavigationPageAttribute : Attribute
{
/// <summary>
/// 视图名称(导航用)
/// </summary>
public string ViewName { get; set; } = "";
/// <summary>
/// Display名称
/// </summary>
public string DisplayName { get; set; } = "";
/// <summary>
/// 排序序号
/// </summary>
public int Index { get; set; }
}
/// <summary>
/// 标志此特性的类会被注册为弹出窗口
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DialogAttribute : Attribute
{
}

View File

@ -1,61 +0,0 @@
using Prism.Events;
namespace SopHelper.Core.Prism;
/// <summary>
/// 全局消息事件(照搬 plcsharp:模块间解耦都走事件聚合器)
/// </summary>
public class MessageEvent : PubSubEvent<Message>
{
}
/// <summary>
/// 消息内容
/// </summary>
public struct Message
{
/// <summary>
/// 消息目标
/// </summary>
public string Target { get; set; }
/// <summary>
/// 消息
/// </summary>
public string Content { get; set; }
/// <summary>
/// 消息类型 1 记录 2 弹出 3 弹出并记录
/// </summary>
public ShowType Type { get; set; }
/// <summary>
/// 级别
/// </summary>
public MsgLevel Level { get; set; }
}
/// <summary>
/// 显示方式
/// </summary>
public enum ShowType
{
/// <summary>仅记录日志</summary>
Log = 1,
/// <summary>仅提示</summary>
Show = 2,
/// <summary>提示并记录</summary>
Both = 3,
}
/// <summary>
/// 消息级别
/// </summary>
public enum MsgLevel
{
Info,
Warn,
Error,
}

View File

@ -1,48 +0,0 @@
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
namespace SopHelper.Core.Prism;
/// <summary>
/// 模型Base
/// </summary>
public class ModelBase : BindableBase
{
/// <summary>
/// 事件聚合器
/// </summary>
protected readonly IEventAggregator _eventAggregator;
/// <summary>
/// DI 容器
/// </summary>
protected readonly IContainerExtension _container;
/// <summary>
/// 模型Base
/// </summary>
public ModelBase(IContainerExtension container, IEventAggregator ea)
{
_container = container;
_eventAggregator = ea;
_eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessage, ThreadOption.PublisherThread, true);
AppDomain.CurrentDomain.ProcessExit += OnExit;
}
/// <summary>
/// 收到消息(子类覆写做本模块的落库/统计)
/// </summary>
protected virtual void OnMessage(Message message)
{
}
/// <summary>
/// 进程退出(子类覆写做释放)
/// </summary>
protected virtual void OnExit(object? sender, EventArgs e)
{
}
}

View File

@ -1,31 +0,0 @@
using Prism.Mvvm;
namespace SopHelper.Core.Prism;
/// <summary>
/// Navigate项
/// </summary>
public class NavigateItem : BindableBase
{
private string _viewName = "";
/// <summary>
/// 视图名称
/// </summary>
public string ViewName
{
get { return _viewName; }
set { SetProperty(ref _viewName, value); }
}
private string _displayName = "";
/// <summary>
/// Display名称
/// </summary>
public string DisplayName
{
get { return _displayName; }
set { SetProperty(ref _displayName, value); }
}
}

View File

@ -1,17 +0,0 @@
using Prism.Mvvm;
using Prism.Navigation;
namespace SopHelper.Core.Prism;
/// <summary>
/// 视图模型Base
/// </summary>
public abstract class ViewModelBase : BindableBase, IDestructible
{
/// <summary>
/// Destroy
/// </summary>
public virtual void Destroy()
{
}
}

View File

@ -1,80 +0,0 @@
using System.Collections.ObjectModel;
using Prism.Events;
using Prism.Ioc;
using Prism.Navigation.Regions;
using SopHelper.Core.Prism;
namespace SopHelper.Models;
/// <summary>
/// Navigate模型
/// </summary>
[Model]
public class NavigationModel : ModelBase
{
private readonly IRegionManager _regionManager;
/// <summary>
/// Navigate模型
/// </summary>
public NavigationModel(IContainerExtension container, IEventAggregator ea, IRegionManager regionManager)
: base(container, ea)
{
_regionManager = regionManager;
}
private ObservableCollection<NavigateItem> _pages = [];
/// <summary>
/// 导航页列表(shell 侧栏绑定)
/// </summary>
public ObservableCollection<NavigateItem> Pages
{
get { return _pages; }
set { SetProperty(ref _pages, value); }
}
private NavigateItem? _target;
/// <summary>
/// 当前页
/// </summary>
public NavigateItem? Target
{
get { return _target; }
set { SetProperty(ref _target, value); }
}
private int _selectedIndex = -1;
/// <summary>
/// 侧栏选中索引
/// </summary>
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (!SetProperty(ref _selectedIndex, value)) return;
if (value >= 0 && value < Pages.Count) Navigate(Pages[value].ViewName);
}
}
/// <summary>
/// 导航到指定页
/// </summary>
public void Navigate(string viewName)
{
if (string.IsNullOrEmpty(viewName)) return;
Target = Pages.FirstOrDefault(n => n.ViewName == viewName);
if (Target is null) return;
_regionManager.RequestNavigate(ContentRegion, viewName);
}
/// <summary>
/// 内容区名(shell 与导航的唯一约定)
/// </summary>
public const string ContentRegion = "ContentRegion";
}

View File

@ -1,42 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<PlatformTarget>x64</PlatformTarget>
<Platforms>AnyCPU;x64</Platforms>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>SopHelper</RootNamespace>
<AssemblyName>SopHelper</AssemblyName>
</PropertyGroup>
<ItemGroup>
<!-- 骨架与 plcsharp 一致:Prism.DryIoc,不引 HandyControl / SkiaSharp.Views.WPF -->
<PackageReference Include="Prism.DryIoc" Version="9.0.537" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SopHelper.Engine\SopHelper.Engine.csproj" />
</ItemGroup>
<!-- 模型文件不入 git,构建时从仓库根目录带到输出目录(照搬参考项目的做法) -->
<ItemGroup>
<None Include="..\..\models\**\*.onnx" Link="models\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<None Include="..\..\yolo_models\**\*.onnx" Link="yolo_models\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\configs\**\*.*" Link="configs\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<Content Include="../../python/**/*" Exclude="../../python/**/*.lnk;../../python/**/__pycache__/**;../../python/**/*.pyc" Link="python/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../tools/worker.py" Link="tools/worker.py" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../tools/Setup-Python.ps1" Link="tools/Setup-Python.ps1" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../tools/requirements.txt" Link="tools/requirements.txt" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -1,332 +0,0 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- 纯 WPF 样式,不依赖任何控件库 -->
<SolidColorBrush x:Key="Bg" Color="#FF101820" />
<SolidColorBrush x:Key="Panel" Color="#FF16222E" />
<SolidColorBrush x:Key="Line" Color="#FF2C4257" />
<SolidColorBrush x:Key="Fg" Color="#FFDCEBF5" />
<SolidColorBrush x:Key="FgDim" Color="#FF8FAFC4" />
<SolidColorBrush x:Key="Accent" Color="#FF00B8D4" />
<SolidColorBrush x:Key="Ok" Color="#FF37B26D" />
<SolidColorBrush x:Key="Ng" Color="#FFF0533C" />
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="Title"
BasedOn="{StaticResource {x:Type TextBlock}}"
TargetType="TextBlock">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="{StaticResource Accent}" />
</Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="10" />
</Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="5">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--
ComboBox:WPF 默认模板是白底(SystemColors.WindowBrush),深色主题下
浅色字落在白底上等于看不见——实测"选不了相机"就是这个。整体重写。
-->
<Style TargetType="ComboBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Height" Value="28" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ToggleButton ClickMode="Press" Focusable="False"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<Border Padding="0"
Background="{StaticResource Panel}"
BorderBrush="{StaticResource Line}"
BorderThickness="1" CornerRadius="4">
<Path Margin="0,0,8,0" HorizontalAlignment="Right"
VerticalAlignment="Center" Data="M 0 0 L 8 0 L 4 5 Z"
Fill="{StaticResource FgDim}" />
</Border>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ContentPresenter Margin="8,0,24,0" VerticalAlignment="Center"
Content="{TemplateBinding SelectionBoxItem}"
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
IsHitTestVisible="False" />
<Popup AllowsTransparency="True" Focusable="False"
IsOpen="{TemplateBinding IsDropDownOpen}"
Placement="Bottom" PopupAnimation="Slide">
<Border MinWidth="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}"
Background="{StaticResource Panel}"
BorderBrush="{StaticResource Line}"
BorderThickness="1">
<ScrollViewer MaxHeight="240">
<StackPanel IsItemsHost="True" />
</ScrollViewer>
</Border>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBoxItem">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Padding" Value="8,6" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Border x:Name="bd"
Padding="{TemplateBinding Padding}"
Background="Transparent">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="#22FFFFFF" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--
TextBox:同 ComboBox,WPF 默认模板是白底。配方编辑器满屏都是输入框,
不重写就是深底白框一片花。
-->
<Style TargetType="TextBox">
<!-- 模板内部 Border 必须显式绑定 Padding,避免继承全局面板的 10px 内边距。 -->
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="CaretBrush" Value="{StaticResource Accent}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="Padding" Value="6,3" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="SelectionBrush" Value="{StaticResource Accent}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
<ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- CheckBox:默认模板浅色主题底,同理重写 -->
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<StackPanel Orientation="Horizontal">
<Border x:Name="box" Width="16" Height="16" Padding="0"
VerticalAlignment="Center"
Background="{StaticResource Panel}"
BorderBrush="{StaticResource Line}"
BorderThickness="1" CornerRadius="3">
<Path x:Name="tick" Width="10" Height="10"
Data="M 0 4 L 3 8 L 10 0 L 12 2 L 4 11 L 1 7 Z"
Fill="{StaticResource Accent}"
Stretch="Fill" Visibility="Collapsed" />
</Border>
<ContentPresenter Margin="6,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="tick" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="box" Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- TabControl:默认模板是浅色主题底(同 ComboBox 那个坑),配方编辑器要用它分区。 -->
<Style TargetType="TabControl">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TabPanel Grid.Row="0" Margin="0,0,0,6" IsItemsHost="True" />
<Border Grid.Row="1"
Background="{StaticResource Panel}"
BorderBrush="{StaticResource Line}"
BorderThickness="1" CornerRadius="6">
<ContentPresenter ContentSource="SelectedContent" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="TabItem">
<Setter Property="Foreground" Value="{StaticResource FgDim}" />
<Setter Property="FontFamily" Value="Microsoft YaHei" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Border x:Name="bd" Margin="0,0,6,0"
Padding="{TemplateBinding Padding}"
Background="Transparent"
BorderBrush="{StaticResource Line}"
BorderThickness="1" CornerRadius="5">
<ContentPresenter VerticalAlignment="Center" ContentSource="Header" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
<Setter TargetName="bd" Property="BorderBrush" Value="{StaticResource Accent}" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="BorderBrush" Value="{StaticResource Accent}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 表单里的字段标签列 -->
<Style x:Key="Field"
BasedOn="{StaticResource {x:Type TextBlock}}"
TargetType="TextBlock">
<Setter Property="Width" Value="74" />
<Setter Property="Foreground" Value="{StaticResource FgDim}" />
</Style>
<!-- 左侧导航 -->
<Style TargetType="ListBox">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="12,10" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="bd"
Padding="{TemplateBinding Padding}"
Background="Transparent" CornerRadius="5">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="#22FFFFFF" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14" Text="{Binding DisplayName}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

View File

@ -1,67 +0,0 @@
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace SopHelper.Training;
/// <summary>Aspect-fit preview with original-image coordinates, including letterbox offsets.</summary>
public sealed class AnnotationCanvas : FrameworkElement
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(nameof(Source), typeof(BitmapSource), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty BoxProperty = DependencyProperty.Register(nameof(Box), typeof(double[]), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public BitmapSource? Source { get => (BitmapSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); }
public double[]? Box { get => (double[]?)GetValue(BoxProperty); set => SetValue(BoxProperty, value); }
public event Action<double[]>? BoxDrawn;
private Point? _start;
private Point _end;
public AnnotationCanvas() { ClipToBounds = true; Cursor = Cursors.Cross; Focusable = true; }
private Rect ImageRect
{
get
{
if (Source == null) return Rect.Empty;
var scale = Math.Min(ActualWidth / Source.PixelWidth, ActualHeight / Source.PixelHeight);
var w = Source.PixelWidth * scale; var h = Source.PixelHeight * scale;
return new Rect((ActualWidth - w) / 2, (ActualHeight - h) / 2, w, h);
}
}
protected override void OnRender(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));
var image = ImageRect;
if (Source == null || image.IsEmpty) return;
dc.DrawImage(Source, image);
var pen = new Pen(new SolidColorBrush(Color.FromRgb(0, 220, 220)), 2);
if (Box is { Length: 4 } b)
{
var scale = image.Width / Source.PixelWidth;
dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30, 0, 220, 220)), pen,
new Rect(image.X + b[0]*scale, image.Y + b[1]*scale, (b[2]-b[0])*scale, (b[3]-b[1])*scale));
}
if (_start is { } start) dc.DrawRectangle(null, new Pen(Brushes.Yellow, 2), new Rect(start, _end));
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!IsEnabled || Source == null || !ImageRect.Contains(e.GetPosition(this))) return;
Focus(); _start = _end = e.GetPosition(this); CaptureMouse(); InvalidateVisual(); e.Handled = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (_start == null) return;
var p = e.GetPosition(this); var image = ImageRect;
_end = new Point(Math.Clamp(p.X, image.Left, image.Right), Math.Clamp(p.Y, image.Top, image.Bottom));
InvalidateVisual();
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (_start is not { } start || Source == null) return;
var rectangle = new Rect(start, _end); var image = ImageRect;
_start = null; ReleaseMouseCapture(); InvalidateVisual();
if (rectangle.Width < 3 || rectangle.Height < 3 || image.Width <= 0) return;
var scale = Source.PixelWidth / image.Width;
BoxDrawn?.Invoke([(rectangle.Left-image.Left)*scale, (rectangle.Top-image.Top)*scale,
Math.Min(Source.PixelWidth, (rectangle.Right-image.Left)*scale), Math.Min(Source.PixelHeight, (rectangle.Bottom-image.Top)*scale)]);
}
protected override void OnLostMouseCapture(MouseEventArgs e) { _start = null; InvalidateVisual(); base.OnLostMouseCapture(e); }
}

View File

@ -1,288 +0,0 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Win32;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using Prism.Commands;
using Prism.Mvvm;
namespace SopHelper.Training;
public sealed class CameraViewModel : BindableBase
{
private readonly ICameraService _camera;
private readonly VideoRecorder _recorder = new();
private readonly object _frames = new();
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _timer;
private readonly string _settingsPath;
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
private Mat? _latest;
private int _previewPending;
private int _generation;
private long _lastFrameTick;
private volatile bool _closing;
private bool _busy, _previewing, _recording;
private string _status = "刷新设备列表,选择相机后开启预览";
private string _directory;
private string _lastRecording = "";
private string _recordingInfo = "未录像";
private CameraInfo? _selected;
private BitmapSource? _preview;
private Task _operation = Task.CompletedTask;
private Task? _shutdown;
private readonly List<DelegateCommand> _commands = [];
public ObservableCollection<CameraInfo> Cameras { get; } = [];
public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } }
public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
public string Status { get => _status; private set => SetProperty(ref _status, value); }
public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } }
public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } }
public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } }
public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing;
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
public string RecordButtonText => IsRecording ? "停止录像" : "开始录像";
public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); }
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); }
public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } }
public double RecordingFps { get; set; } = 30;
public DelegateCommand RefreshCommand { get; }
public DelegateCommand PreviewCommand { get; }
public DelegateCommand RecordCommand { get; }
public DelegateCommand BrowseCommand { get; }
public DelegateCommand RevealCommand { get; }
public CameraViewModel(ICameraService camera, string root)
{
_camera = camera; _dispatcher = Application.Current.Dispatcher;
_directory = Path.Combine(root, "workspace", "recordings");
_settingsPath = Path.Combine(root, "workspace", "camera-settings.json");
try
{
if (File.Exists(_settingsPath))
{
using var json = JsonDocument.Parse(File.ReadAllText(_settingsPath));
SaveDirectory = json.RootElement.GetProperty("directory").GetString() ?? _directory;
}
}
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);
PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null));
RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame)));
BrowseCommand = Command(() =>
{
var picker = new OpenFolderDialog { Title = "选择录像保存目录" };
if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory;
if (picker.ShowDialog() == true) { SaveDirectory = picker.FolderName; SaveSettings(); }
return Task.CompletedTask;
}, () => CanChangeDirectory);
RevealCommand = Command(() =>
{
if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording))
{
var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
info.ArgumentList.Add("/select," + LastRecording); Process.Start(info);
}
else
{
Directory.CreateDirectory(SaveDirectory);
var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info);
}
return Task.CompletedTask;
}, () => !IsBusy && !_closing);
_camera.FrameArrived += OnFrame;
_camera.ConnectionChanged += OnConnection;
_camera.Error += OnError;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
_timer.Start();
}
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)
{
var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute);
_commands.Add(command); return command;
}
private async Task PerformAsync(Func<Task> action)
{
if (IsBusy || _closing) return;
IsBusy = true;
try { await action(); }
catch (Exception e) { Status = e.Message; }
finally { IsBusy = false; }
}
private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); }
private void StateChanged()
{
RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory));
RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands();
}
private async Task RefreshAsync()
{
Status = "正在枚举 UVC / 海康相机…";
var devices = await _camera.EnumerateAsync();
if (_closing) return;
Cameras.Clear(); foreach (var device in devices) Cameras.Add(device);
SelectedCamera = Cameras.FirstOrDefault();
Status = Cameras.Count == 0 ? "未找到相机,请检查连接;海康设备需要 MVS x64 运行时" : $"找到 {Cameras.Count} 台相机";
}
private async Task TogglePreviewAsync()
{
if (IsPreviewing)
{
StopRecording();
await Task.Run(_camera.Disconnect);
ClearPreview(); IsPreviewing = false; Status = "相机已关闭";
return;
}
var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机");
Status = "正在连接 " + selected.Name;
if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
if (_closing) return;
if (!await _camera.StartAsync())
{
await Task.Run(_camera.Disconnect);
throw new IOException("相机已连接,但采集启动失败");
}
IsPreviewing = true; Status = "相机预览中,可开始录像";
}
private Task ToggleRecordingAsync()
{
if (IsRecording) { StopRecording(); return Task.CompletedTask; }
if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录");
var directory = Path.GetFullPath(SaveDirectory.Trim());
SaveDirectory = directory; SaveSettings();
lock (_frames)
{
if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览");
if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
LastRecording = _recorder.Start(directory, _latest, RecordingFps);
}
IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick();
return Task.CompletedTask;
}
private void StopRecording()
{
RecordingResult? result;
lock (_frames) result = _recorder.Stop();
IsRecording = false;
if (result != null)
{
LastRecording = result.Path;
RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
Status = "录像已保存,可在主窗口导入视频继续标注";
}
}
private void OnFrame(CameraFrame frame)
{
if (_closing) return;
BitmapSource? preview = null;
string? recordingError = null;
var generation = Volatile.Read(ref _generation);
lock (_frames)
{
if (_closing) return;
Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp());
if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest);
try { _recorder.Write(frame.Bgr); }
catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; }
if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0)
{
try
{
var stride = checked((int)frame.Bgr.Step());
preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24,
null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride);
preview.Freeze(); _previewClock.Restart();
}
catch { Interlocked.Exchange(ref _previewPending, 0); throw; }
}
}
if (recordingError != null)
{
var error = recordingError;
Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; });
}
if (preview != null)
{
var bitmap = preview;
Post(() =>
{
try
{
if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); }
}
finally { Interlocked.Exchange(ref _previewPending, 0); }
});
}
}
private void OnConnection(bool connected)
{
if (!connected) Post(() =>
{
if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection.
StopRecording(); IsPreviewing = false; ClearPreview();
});
}
private void OnError(string message) => Post(() => Status = message);
private void Post(Action action)
{
if (!_closing && !_dispatcher.HasShutdownStarted)
_dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background);
}
private void Tick()
{
if (_closing) return;
if (IsRecording)
{
if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2)
{
StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接";
}
else if (!_recorder.IsRecording) IsRecording = false;
else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps";
}
if (IsPreviewing && !_camera.IsGrabbing && !IsBusy)
{
StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接";
}
}
private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 &&
Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2;
private void ClearPreview()
{
Interlocked.Increment(ref _generation);
lock (_frames) { _latest?.Dispose(); _latest = null; }
Preview = null;
}
private void SaveSettings()
{
Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!);
File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory }));
}
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
private async Task ShutdownCoreAsync()
{
_closing = true; _timer.Stop(); StateChanged();
await _operation;
try { await Task.Run(_camera.Dispose); }
finally
{
try { StopRecording(); }
finally
{
ClearPreview();
_camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError;
IsPreviewing = false;
}
}
}
}

View File

@ -1,40 +0,0 @@
<Window x:Class="SopHelper.Training.CameraWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SopHelper · 相机与录像" Width="1080" Height="800" MinWidth="840" MinHeight="650" WindowStartupLocation="CenterOwner"
Style="{DynamicResource {x:Type Window}}">
<Window.Resources><ResourceDictionary Source="/SopHelper;component/Training/Styles.xaml"/></Window.Resources>
<Grid Margin="18">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<TextBlock Text="相机与录像" FontSize="22" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,0,0,16"/>
<Grid Grid.Row="1" Margin="0,0,0,10">
<Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera}" IsEnabled="{Binding CanChooseCamera}" Margin="0,0,10,6" MinHeight="36">
<ComboBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Name}"/></DataTemplate></ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="刷新相机" Command="{Binding RefreshCommand}"/>
<Button Grid.Column="2" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}"/>
</Grid>
<Border Grid.Row="2" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6">
<Grid>
<TextBlock Text="开启相机后在此显示实时画面" HorizontalAlignment="Center" Foreground="{StaticResource Dim}"/>
<Image Source="{Binding Preview}" Stretch="Uniform"/>
<Border HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12" Padding="10,5" Background="#CC101820" CornerRadius="4"><TextBlock Text="{Binding RecordingInfo}"><TextBlock.Style><Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"><Setter Property="Foreground" Value="{StaticResource Dim}"/><Style.Triggers><DataTrigger Binding="{Binding IsRecording}" Value="True"><Setter Property="Foreground" Value="#F0533C"/></DataTrigger></Style.Triggers></Style></TextBlock.Style></TextBlock></Border>
</Grid>
</Border>
<StackPanel Grid.Row="3" Margin="0,14,0,0">
<TextBlock Text="录像保存目录"/>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBox Text="{Binding SaveDirectory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeDirectory}" Margin="0,6,10,8"/>
<Button Grid.Column="1" Content="选择目录…" Command="{Binding BrowseCommand}" Margin="0,6,6,8"/>
<Button Grid.Column="2" Content="打开保存位置" Command="{Binding RevealCommand}" Margin="0,6,0,8"/>
</Grid>
<DockPanel>
<Button DockPanel.Dock="Left" Content="{Binding RecordButtonText}" Command="{Binding RecordCommand}" BorderBrush="{StaticResource Accent}" MinWidth="130"/>
<TextBlock Text="AVI / MJPEG · 30 fps · 原始画面,不含标注和界面" Foreground="{StaticResource Dim}" Margin="12,0,0,6"/>
</DockPanel>
<TextBlock Text="{Binding LastRecording}" TextTrimming="CharacterEllipsis" ToolTip="{Binding LastRecording}" Foreground="{StaticResource Dim}" Margin="0,0,0,8"/>
</StackPanel>
<TextBlock Grid.Row="4" Text="{Binding Status}" TextWrapping="Wrap" Margin="0,8,0,0"/>
</Grid>
</Window>

View File

@ -1,27 +0,0 @@
using System.ComponentModel;
using System.Windows;
namespace SopHelper.Training;
public partial class CameraWindow : Window
{
public CameraViewModel Model { get; }
private bool _closedSafely;
private bool _closeRequested;
public CameraWindow(CameraViewModel model)
{
InitializeComponent(); Model = model; DataContext = model;
}
protected override async void OnClosing(CancelEventArgs e)
{
if (_closedSafely) { base.OnClosing(e); return; }
e.Cancel = true;
base.OnClosing(e);
if (_closeRequested) return;
_closeRequested = true;
IsEnabled = false;
try { await Model.ShutdownAsync(); }
catch (Exception error) { MessageBox.Show(this, "关闭相机时出错:" + error.Message, "相机与录像"); }
_ = Dispatcher.BeginInvoke(() => { _closedSafely = true; Close(); });
}
}

View File

@ -1,366 +0,0 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using SopHelper.Engine.Training;
using Prism.Commands;
using Prism.Mvvm;
namespace SopHelper.Training;
public sealed class MainViewModel : BindableBase
{
private readonly WorkerClient _worker;
private CancellationTokenSource? _cancellation;
private TaskCompletionSource? _completion;
private TrainingProject? _project;
private FrameAnnotation? _selected;
private BitmapImage? _preview;
private bool _busy;
private double _progress;
private string _status = "新建项目:导入视频,在任意清晰帧拖动画框";
private string _logs = "";
private bool _isTraining;
private string _trainingStatus = "打开已复核项目后即可开始训练";
private string _trainingMetrics = "尚无训练指标";
private string _latestWeights = "";
private string _trainingRunDirectory = "";
public bool IsTraining { get => _isTraining; private set => SetProperty(ref _isTraining, value); }
public string TrainingStatus { get => _trainingStatus; private set => SetProperty(ref _trainingStatus, value); }
public string TrainingMetrics { get => _trainingMetrics; private set => SetProperty(ref _trainingMetrics, value); }
public string LatestWeights { get => _latestWeights; private set => SetProperty(ref _latestWeights, value); }
public string TrainingRunDirectory { get => _trainingRunDirectory; private set => SetProperty(ref _trainingRunDirectory, value); }
public string TrainingOutputDirectory { get; set; } = "";
public string Root { get; }
public TrainingProject? Project => _project;
public ObservableCollection<FrameAnnotation> Frames { get; } = [];
public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); } }
public bool IsIdle => !IsBusy;
public double Progress { get => _progress; set => SetProperty(ref _progress, value); }
public string Status { get => _status; set => SetProperty(ref _status, value); }
public string Logs { get => _logs; set => SetProperty(ref _logs, value); }
public string Summary => _project == null ? "尚未导入视频" : $"{_project.Width} × {_project.Height} · {Frames.Count} 帧 · 已复核 {Frames.Count(f => f.Status is "reviewed" or "absent")} · 待复核 {Frames.Count(f => f.Status == "auto")}";
public string FrameInfo => _selected == null || _project == null ? "拖动画框以标记零件" : $"第 {_selected.Index + 1} 帧 · 原视频帧 {_selected.SourceIndex} · {(_project.Fps > 0 ? (_selected.SourceIndex / _project.Fps).ToString("F2") + " 秒" : "时间未知")} · {_selected.Display}";
public string ProjectPath => _project?.FilePath ?? "项目会自动保存到你选择的文件夹";
public BitmapImage? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
public double[]? CurrentBox => _selected?.Box;
public FrameAnnotation? SelectedFrame
{
get => _selected;
set
{
if (!SetProperty(ref _selected, value)) return;
try
{
if (value != null && _project != null)
{
var bitmap = new BitmapImage();
bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(Path.Combine(_project.DirectoryPath, value.Image));
bitmap.EndInit(); bitmap.Freeze(); Preview = bitmap;
}
}
catch (Exception e) { Status = "图像读取失败:" + e.Message; Preview = null; }
RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo));
}
}
// Configuration is saved locally, except the API key which is passed only through the worker environment.
private static string PythonPath => Path.Combine(AppContext.BaseDirectory, "python", "python.exe");
public string Label { get; set; } = "零件";
public int ExtractStride { get; set; } = 1;
public int MaxFrames { get; set; } = 600;
public string Checkpoint { get; set; } = "";
public string SamConfig { get; set; } = "configs/sam2.1/sam2.1_hiera_t.yaml";
public string Device { get; set; } = "auto";
public int ExportEvery { get; set; } = 5;
public int Epochs { get; set; } = 50;
public int Batch { get; set; } = 4;
public int ImageSize { get; set; } = 640;
public string Model { get; set; } = "yolo11n.pt";
public string Endpoint { get; set; } = "https://api.example.com/v1";
public string ApiModel { get; set; } = "";
public string Description { get; set; } = "";
public Func<string>? ReadApiKey { get; set; }
public DelegateCommand ImportCommand { get; }
public DelegateCommand OpenCommand { get; }
public DelegateCommand DoctorCommand { get; }
public DelegateCommand PropagateCommand { get; }
public DelegateCommand ExportCommand { get; }
public DelegateCommand TrainCommand { get; }
public DelegateCommand PickTrainingModelCommand { get; }
public DelegateCommand PickTrainingOutputCommand { get; }
public DelegateCommand OpenTrainingResultsCommand { get; }
public DelegateCommand OnnxCommand { get; }
public DelegateCommand SuggestCommand { get; }
public DelegateCommand ApproveCommand { get; }
public DelegateCommand ApproveAllCommand { get; }
public DelegateCommand AbsentCommand { get; }
public DelegateCommand ExcludeCommand { get; }
public DelegateCommand PreviousCommand { get; }
public DelegateCommand NextCommand { get; }
public DelegateCommand CancelCommand { get; }
public DelegateCommand RevealCommand { get; }
private List<DelegateCommand> Commands { get; } = [];
public MainViewModel(WorkerClient worker)
{
_worker = worker;
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx"))) directory = directory.Parent;
Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx")) ? directory.FullName : AppContext.BaseDirectory;
LoadSettings();
ImportCommand = Command(Import);
OpenCommand = Command(() =>
{
var dialog = new OpenFileDialog { Filter = "标注项目|project.json" };
if (dialog.ShowDialog() == true) Load(dialog.FileName);
});
DoctorCommand = Command(async () => await Run(new { action = "doctor" }, reload: false));
PropagateCommand = Command(async () => { SaveLabel(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); });
ExportCommand = Command(async () => { SaveLabel(); await Run(Request("export")); });
TrainCommand = Command(async () => { SaveLabel(); await Run(Request("train")); });
PickTrainingModelCommand = Command(() =>
{
var dialog = new OpenFileDialog { Filter = "YOLO模型|*.pt;*.yaml;*.yml" };
if (dialog.ShowDialog() == true) { Model = dialog.FileName; RaisePropertyChanged(nameof(Model)); }
});
PickTrainingOutputCommand = Command(() =>
{
var dialog = new OpenFolderDialog { Title = "选择训练结果保存目录" };
if (dialog.ShowDialog() == true) { TrainingOutputDirectory = dialog.FolderName; RaisePropertyChanged(nameof(TrainingOutputDirectory)); }
});
OpenTrainingResultsCommand = Command(() =>
{
var directory = TrainingRunDirectory;
if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练");
Process.Start(new ProcessStartInfo("explorer.exe") { ArgumentList = { directory }, UseShellExecute = true });
});
OnnxCommand = Command(async () => await Run(Request("onnx")));
SuggestCommand = Command(async () =>
{
SaveLabel();
if (SelectedFrame == null) throw new InvalidOperationException("请先选择帧");
await Run(new { action = "suggest", project = RequireProject().FilePath, index = SelectedFrame.Index,
endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke());
});
ApproveCommand = Command(() => Update("reviewed"));
ApproveAllCommand = Command(ApproveAll);
AbsentCommand = Command(() => Update("absent"));
ExcludeCommand = Command(() => Update("excluded"));
PreviousCommand = Command(() => Move(-1));
NextCommand = Command(() => Move(1));
CancelCommand = new DelegateCommand(() => _cancellation?.Cancel());
RevealCommand = Command(() => Process.Start(new ProcessStartInfo("explorer.exe") { ArgumentList = { _project?.DirectoryPath ?? Root }, UseShellExecute = true }));
}
private DelegateCommand Command(Action action)
{
var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => !IsBusy);
Commands.Add(command); return command;
}
private DelegateCommand Command(Func<Task> action)
{
var command = new DelegateCommand(async () =>
{
try { await action(); }
catch (Exception e) { Status = e.Message; Append(e.Message); }
}, () => !IsBusy);
Commands.Add(command); return command;
}
// Async operations catch their own exceptions inside Run. Import does synchronous validation before awaiting.
private object Request(string action) => new { action, project = RequireProject().FilePath, every = ExportEvery,
valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = Model, device = Device,
outputDirectory = TrainingOutputDirectory };
private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
private void SaveLabel()
{
var project = RequireProject();
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
project.Name = Label.Trim(); project.Save();
}
private async void Import()
{
try
{
var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" };
if (video.ShowDialog() != true) return;
var folder = new OpenFolderDialog { Title = "选择项目保存的父文件夹(会自动新建子文件夹)" };
if (folder.ShowDialog() != true) return;
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
var output = Path.Combine(folder.FolderName, "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
if (await Run(new { action = "extract", video = video.FileName, output, name = Label.Trim(), stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
Load(Path.Combine(output, "project.json"));
}
catch (Exception e) { Status = e.Message; Append(e.Message); }
}
public void Load(string path, int index = 0)
{
_project = TrainingProject.Load(path);
Label = _project.Name; RaisePropertyChanged(nameof(Label));
_selected = null; Frames.Clear();
foreach (var frame in _project.Frames) Frames.Add(frame);
SelectedFrame = Frames[Math.Clamp(index, 0, Frames.Count - 1)];
RaisePropertyChanged(nameof(Summary)); RaisePropertyChanged(nameof(ProjectPath));
LoadTrainingResult();
if (!IsBusy) Status = "项目已打开;拖动画框或选择帧进行复核";
}
public void DrawBox(double[] box)
{
if (IsBusy || SelectedFrame == null || _project == null) return;
try
{
_project.ValidateBox(box); SelectedFrame.Box = box; SelectedFrame.Prompt = true;
SelectedFrame.Status = "reviewed"; _project.Save(); Refresh();
Status = "关键帧已保存;可再选其他角度画框,或开始 SAM2 传播";
}
catch (Exception e) { Status = e.Message; }
}
private void Update(string status)
{
if (SelectedFrame == null) return;
if (status == "reviewed" && SelectedFrame.Box == null) throw new InvalidOperationException("该帧没有目标框,请画框或标记无目标");
SelectedFrame.Status = status;
if (status != "reviewed") { SelectedFrame.Box = null; SelectedFrame.Prompt = false; }
RequireProject().Save(); Refresh();
Status = "当前帧已保存";
}
private void ApproveAll()
{
var project = RequireProject();
var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Box != null).ToList();
// Validate the whole batch before changing any annotation status.
foreach (var frame in pending) project.ValidateBox(frame.Box!);
if (pending.Count == 0) { Status = "没有带目标框的待复核帧"; return; }
var selectedIndex = SelectedFrame?.Index ?? 0;
foreach (var frame in pending) frame.Status = "reviewed";
try { project.Save(); }
catch
{
foreach (var frame in pending) frame.Status = "auto";
throw;
}
Load(project.FilePath, selectedIndex);
Status = $"一键复核完成:已确认 {pending.Count} 帧并保存";
}
private void Refresh()
{
var frame = SelectedFrame;
if (frame == null) return;
var index = Frames.IndexOf(frame); Frames[index] = frame;
SelectedFrame = frame;
RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo)); RaisePropertyChanged(nameof(Summary));
}
private void Move(int delta)
{
if (Frames.Count > 0) SelectedFrame = Frames[Math.Clamp(Frames.IndexOf(SelectedFrame!) + delta, 0, Frames.Count - 1)];
}
private void Append(string line)
{
Application.Current.Dispatcher.Invoke(() =>
{
Logs += line + Environment.NewLine;
if (Logs.Length > 40000) Logs = Logs[^30000..];
});
}
private async Task<bool> Run(object request, bool reload = true, string? apiKey = null)
{
if (IsBusy) return false;
IsTraining = JsonSerializer.SerializeToElement(request).GetProperty("action").GetString() == "train";
if (IsTraining) { TrainingStatus = "正在准备数据与模型…"; TrainingMetrics = "等待首轮训练指标"; }
IsBusy = true; Progress = 0; Status = "任务运行中…";
_cancellation = new CancellationTokenSource();
_completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var path = _project?.FilePath; var index = SelectedFrame?.Index ?? 0;
try
{
SaveSettings();
if (!File.Exists(PythonPath))
throw new FileNotFoundException("缺少内置 Python 环境,请运行 tools/Setup-Python.ps1 -Sam2 后重新构建程序。", PythonPath);
await _worker.RunAsync(PythonPath, Path.Combine(Root, "tools", "worker.py"), request, line =>
{
try
{
using var json = JsonDocument.Parse(line);
var item = json.RootElement;
var message = item.TryGetProperty("message", out var m) ? m.GetString() ?? line : line;
Append(message);
Application.Current.Dispatcher.Invoke(() =>
{
Status = message;
if (item.TryGetProperty("progress", out var progress) && (!IsTraining || item.TryGetProperty("event", out _))) Progress = Math.Clamp(progress.GetDouble(), 0, 1) * 100;
if (IsTraining)
{
TrainingStatus = message;
if (item.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
if (item.TryGetProperty("runDirectory", out var directory)) TrainingRunDirectory = directory.GetString() ?? "";
if (item.TryGetProperty("weights", out var weights)) LatestWeights = weights.GetString() ?? "";
}
});
if (item.TryGetProperty("modules", out var modules)) Append(modules.ToString());
if (item.TryGetProperty("output", out var output)) Append(output.GetString() ?? "");
}
catch (Exception e) when (e is JsonException or InvalidOperationException or FormatException) { Append(line); }
}, _cancellation.Token, apiKey);
Progress = 100; return true;
}
catch (OperationCanceledException) { Status = "任务已取消;已保存的标注保留"; if (IsTraining) TrainingStatus = "训练已停止;已写入的日志与检查点保留在结果目录"; Append(Status); return false; }
catch (Exception e) { Status = e.Message; if (IsTraining) TrainingStatus = "训练失败,请查看运行日志:" + e.Message; Append(e.Message); return false; }
finally
{
if (reload && path != null)
{
try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); }
}
_cancellation.Dispose(); _cancellation = null; IsBusy = false; IsTraining = false;
_completion.TrySetResult();
}
}
public void Cancel() => _cancellation?.Cancel();
public async Task StopAsync()
{
Cancel();
if (_completion != null) await _completion.Task;
}
private static string FormatMetrics(JsonElement metrics) => string.Join(Environment.NewLine,
metrics.EnumerateObject().Where(m => m.Value.ValueKind == JsonValueKind.Number)
.Select(m => $"{m.Name}: {m.Value.GetDouble():F4}"));
private void LoadTrainingResult()
{
if (IsTraining) return;
LatestWeights = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
var file = Path.Combine(RequireProject().DirectoryPath, "latest-model.json");
if (!File.Exists(file)) return;
try
{
using var result = JsonDocument.Parse(File.ReadAllText(file));
LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
TrainingRunDirectory = result.RootElement.TryGetProperty("runDirectory", out var directory) ? directory.GetString() ?? "" : Path.GetDirectoryName(Path.GetDirectoryName(LatestWeights)) ?? "";
if (result.RootElement.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
}
catch (Exception e) { Append("读取训练结果失败:" + e.Message); }
}
private void SaveSettings()
{
Directory.CreateDirectory(Path.Combine(Root, "workspace"));
File.WriteAllText(Path.Combine(Root, "workspace", "settings.json"), JsonSerializer.Serialize(new
{ Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, TrainingOutputDirectory, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
}
private void LoadSettings()
{
var path = Path.Combine(Root, "workspace", "settings.json");
if (!File.Exists(path)) return;
try
{
using var settings = JsonDocument.Parse(File.ReadAllText(path));
foreach (var item in settings.RootElement.EnumerateObject())
{
var property = GetType().GetProperty(item.Name);
if (property?.CanWrite == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString());
else if (property?.CanWrite == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32());
}
}
catch (Exception) { Status = "设置文件不可读,已使用默认配置"; }
}
}

View File

@ -1,32 +0,0 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="Bg" Color="#101820"/>
<SolidColorBrush x:Key="Panel" Color="#16222E"/>
<SolidColorBrush x:Key="Line" Color="#2C4257"/>
<SolidColorBrush x:Key="Fg" Color="#DCEBF5"/>
<SolidColorBrush x:Key="Dim" Color="#8FAFC4"/>
<SolidColorBrush x:Key="Accent" Color="#00B8D4"/>
<Style TargetType="Window"><Setter Property="FontFamily" Value="Microsoft YaHei"/><Setter Property="Background" Value="{StaticResource Bg}"/><Setter Property="Foreground" Value="{StaticResource Fg}"/></Style>
<Style TargetType="TextBlock"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="VerticalAlignment" Value="Center"/><Setter Property="FontSize" Value="13"/></Style>
<Style x:Key="Hint" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"><Setter Property="Foreground" Value="{StaticResource Dim}"/><Setter Property="TextWrapping" Value="Wrap"/><Setter Property="Margin" Value="0,6,0,12"/><Setter Property="LineHeight" Value="21"/></Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Background" Value="{StaticResource Panel}"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="12,8"/><Setter Property="Margin" Value="0,0,6,6"/><Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border x:Name="body" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" CornerRadius="5" Padding="{TemplateBinding Padding}"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="body" Property="BorderBrush" Value="{StaticResource Accent}"/></Trigger><Trigger Property="IsEnabled" Value="False"><Setter Property="Opacity" Value="0.35"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
</Style>
<Style TargetType="TextBox"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Background" Value="#101820"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="7"/><Setter Property="Margin" Value="0,4,0,10"/><Setter Property="CaretBrush" Value="{StaticResource Accent}"/></Style>
<Style TargetType="PasswordBox"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Background" Value="#101820"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="7"/><Setter Property="Margin" Value="0,4,0,10"/></Style>
<Style TargetType="TabControl"><Setter Property="Background" Value="{StaticResource Panel}"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="12"/></Style>
<Style TargetType="TabItem"><Setter Property="Foreground" Value="{StaticResource Dim}"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="TabItem"><Border x:Name="tab" Padding="14,10" Background="#101820"><ContentPresenter ContentSource="Header"/></Border><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="Foreground" Value="{StaticResource Accent}"/><Setter TargetName="tab" Property="Background" Value="#16222E"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
<Style TargetType="ListBox"><Setter Property="Background" Value="#101820"/><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/></Style>
<Style TargetType="ListBoxItem"><Setter Property="Padding" Value="10,8"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ListBoxItem"><Border x:Name="item" Background="Transparent" Padding="{TemplateBinding Padding}"><ContentPresenter/></Border><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="True"><Setter TargetName="item" Property="Background" Value="#204B5C"/></Trigger><Trigger Property="IsMouseOver" Value="True"><Setter Property="Foreground" Value="{StaticResource Accent}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
<Style TargetType="ComboBox">
<Setter Property="Foreground" Value="{StaticResource Fg}"/>
<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ComboBox"><Grid>
<ToggleButton Focusable="False" ClickMode="Press" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.Template><ControlTemplate TargetType="ToggleButton"><Border Background="{StaticResource Panel}" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="4"><Path HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0" Data="M 0 0 L 8 0 L 4 5 Z" Fill="{StaticResource Dim}"/></Border></ControlTemplate></ToggleButton.Template>
</ToggleButton>
<ContentPresenter Margin="10,0,28,0" VerticalAlignment="Center" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" IsHitTestVisible="False"/>
<Popup x:Name="PART_Popup" IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" AllowsTransparency="True" Focusable="False"><Border Background="{StaticResource Panel}" BorderBrush="{StaticResource Line}" BorderThickness="1" MinWidth="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}"><ScrollViewer MaxHeight="240"><ItemsPresenter/></ScrollViewer></Border></Popup>
</Grid><ControlTemplate.Triggers><Trigger Property="IsEnabled" Value="False"><Setter Property="Opacity" Value="0.4"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
</Style>
<Style TargetType="ComboBoxItem"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Padding" Value="10,8"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ComboBoxItem"><Border x:Name="row" Background="Transparent" Padding="{TemplateBinding Padding}"><ContentPresenter/></Border><ControlTemplate.Triggers><Trigger Property="IsHighlighted" Value="True"><Setter TargetName="row" Property="Background" Value="#204B5C"/></Trigger><Trigger Property="IsSelected" Value="True"><Setter TargetName="row" Property="Background" Value="#204B5C"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
</ResourceDictionary>

View File

@ -1,76 +0,0 @@
<UserControl x:Class="SopHelper.Training.TrainingPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SopHelper.Training"
>
<UserControl.Resources><ResourceDictionary Source="/SopHelper;component/Training/Styles.xaml"/></UserControl.Resources>
<ScrollViewer Margin="12" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Grid Height="{Binding ViewportHeight, RelativeSource={RelativeSource AncestorType=ScrollViewer}}" MinWidth="1080" MinHeight="720">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="176"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<DockPanel Margin="0,0,0,14">
<StackPanel DockPanel.Dock="Left" Margin="0,0,28,0"><TextBlock Text="零件标注与训练" FontSize="23" FontWeight="Bold" Foreground="{StaticResource Accent}"/><TextBlock Text="视频 → 标注 → 复核 → YOLO" Foreground="{StaticResource Dim}"/></StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center"><Button Content="相机与录像" Click="OpenCameraClicked"/><Button Content="导入视频" Command="{Binding ImportCommand}"/><Button Content="打开项目" Command="{Binding OpenCommand}"/><Button Content="项目文件夹" Command="{Binding RevealCommand}"/><Button Content="取消任务" Command="{Binding CancelCommand}" IsEnabled="{Binding IsBusy}"/></StackPanel>
</DockPanel>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions><ColumnDefinition Width="220"/><ColumnDefinition Width="12"/><ColumnDefinition Width="*"/><ColumnDefinition Width="12"/><ColumnDefinition Width="330"/></Grid.ColumnDefinitions>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Margin="0,0,0,10"><TextBlock Text="视频帧" FontSize="16" FontWeight="Bold"/><TextBlock Text="{Binding Summary}" Style="{StaticResource Hint}"/></StackPanel>
<ListBox ItemsSource="{Binding Frames}" SelectedItem="{Binding SelectedFrame}" IsEnabled="{Binding IsIdle}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Display}" FontSize="12"/></DataTemplate></ListBox.ItemTemplate></ListBox>
</DockPanel>
<Grid Grid.Column="2">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<TextBlock Text="{Binding FrameInfo}" Margin="0,0,0,10" TextWrapping="Wrap"/>
<Border Grid.Row="1" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" ClipToBounds="True">
<local:AnnotationCanvas x:Name="Canvas" Source="{Binding Preview}" Box="{Binding CurrentBox}" IsEnabled="{Binding IsIdle}"/>
</Border>
<WrapPanel Grid.Row="2" Margin="0,12,0,0"><Button Content="← 上一帧" Command="{Binding PreviousCommand}"/><Button Content="下一帧 →" Command="{Binding NextCommand}"/><Button Content="确认当前框" Command="{Binding ApproveCommand}"/><Button Content="一键复核" Command="{Binding ApproveAllCommand}" ToolTip="确认本项目中所有带目标框的待复核帧,并立即保存"/><Button Content="无目标" Command="{Binding AbsentCommand}"/><Button Content="排除此帧" Command="{Binding ExcludeCommand}"/></WrapPanel>
<TextBlock Grid.Row="3" Style="{StaticResource Hint}" Text="拖动画框或修正,自动保存为关键帧。← → 切帧,Enter 确认当前框并进入下一帧。"/>
</Grid>
<TabControl Grid.Column="4" IsEnabled="{Binding IsIdle}">
<TabItem Header="标注"><ScrollViewer VerticalScrollBarVisibility="Auto"><StackPanel>
<TextBlock Text="01 导入旋转视频" FontWeight="Bold" Foreground="{StaticResource Accent}"/>
<TextBlock Text="零件类别名称" Margin="0,12,0,0"/><TextBox Text="{Binding Label, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="抽帧间隔(原视频帧数)"/><TextBox Text="{Binding ExtractStride}"/>
<TextBlock Text="最多导入帧数"/><TextBox Text="{Binding MaxFrames}"/>
<TextBlock Style="{StaticResource Hint}" Text="默认最多600帧;长视频会自动增大间隔覆盖全片。快速旋转建议分成短片导入。"/>
<TextBlock Text="02 画框并自动传播" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,10,0,8"/>
<Button Content="开始 SAM2 传播" Command="{Binding PropagateCommand}" BorderBrush="{StaticResource Accent}"/>
<TextBlock Style="{StaticResource Hint}" Text="先在清晰帧画一个框。旋转幅度大时,可在多个角度补框后再运行。传播保留已复核帧。"/>
<TextBlock Text="03 人工复核" FontWeight="Bold" Foreground="{StaticResource Accent}"/>
<TextBlock Style="{StaticResource Hint}" Text="逐帧确认目标框;框偏了直接重画。无目标用于负样本,排除帧不参与训练。只导出已复核数据。"/>
</StackPanel></ScrollViewer></TabItem>
<TabItem Header="训练"><ScrollViewer VerticalScrollBarVisibility="Auto"><StackPanel>
<TextBlock Text="YOLO 目标检测训练" FontSize="16" FontWeight="Bold"/>
<TextBlock Style="{StaticResource Hint}" Text="按时间分段:前段训练、末尾20%验证,边界留出间隔。正式评估请另拍独立测试视频。"/>
<TextBlock Text="训练抽样间隔(导入后的帧数)"/><TextBox Text="{Binding ExportEvery}"/>
<TextBlock Text="YOLO 初始模型 / 本地 .pt 路径"/><TextBox Text="{Binding Model}"/>
<TextBlock Text="训练轮数"/><TextBox Text="{Binding Epochs}"/>
<TextBlock Text="图像尺寸(32的倍数)"/><TextBox Text="{Binding ImageSize}"/>
<TextBlock Text="批次大小"/><TextBox Text="{Binding Batch}"/>
<Button Content="导出 YOLO 数据集" Command="{Binding ExportCommand}"/>
<Button Content="开始训练" Command="{Binding TrainCommand}" BorderBrush="{StaticResource Accent}"/>
<Button Content="导出最新模型为 ONNX" Command="{Binding OnnxCommand}"/>
<TextBlock Style="{StaticResource Hint}" Text="每次训练重新导出当前复核数据。best.pt、ONNX 和训练指标保存在项目 runs 文件夹。默认 yolo11n,检测框格式便于接入 SopHelper,仍需现场验证。"/>
</StackPanel></ScrollViewer></TabItem>
<TabItem Header="设置"><ScrollViewer VerticalScrollBarVisibility="Auto"><StackPanel>
<Button Content="检查环境与 CUDA" Command="{Binding DoctorCommand}"/>
<TextBlock Text="设备:auto / cpu / cuda(训练可填0)"/><TextBox Text="{Binding Device}"/>
<TextBlock Text="SAM2 checkpoint(留空自动下载 tiny)"/><TextBox Text="{Binding Checkpoint}"/>
<TextBlock Text="SAM2 配置(仅本地 checkpoint 使用)"/><TextBox Text="{Binding SamConfig}"/>
<TextBlock Text="可选:视觉大模型建议框" FontWeight="Bold" Margin="0,12,0,0"/>
<TextBlock Style="{StaticResource Hint}" Text="兼容 chat/completions 的视觉接口。点击时会上传当前帧到下方地址;结果需人工确认,再用于 SAM2 传播。"/>
<TextBlock Text="API Base URL(包含 /v1,不含 /chat/completions)"/><TextBox Text="{Binding Endpoint}"/>
<TextBlock Text="视觉模型名称"/><TextBox Text="{Binding ApiModel}"/>
<TextBlock Text="API Key(仅本次运行,不写入项目)"/><PasswordBox x:Name="ApiKey"/>
<TextBlock Text="零件外观描述"/><TextBox Text="{Binding Description}" AcceptsReturn="True" Height="64" TextWrapping="Wrap"/>
<Button Content="让视觉模型建议当前帧目标框" Command="{Binding SuggestCommand}"/>
</StackPanel></ScrollViewer></TabItem>
</TabControl>
</Grid>
<Grid Grid.Row="2" Margin="0,12,0,0"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
<DockPanel><TextBlock Text="运行日志" Foreground="{StaticResource Dim}"/><TextBlock Text="{Binding ProjectPath}" TextTrimming="CharacterEllipsis" HorizontalAlignment="Right" MaxWidth="850" Foreground="{StaticResource Dim}"/></DockPanel>
<TextBox x:Name="LogBox" Grid.Row="1" Text="{Binding Logs, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" FontFamily="Consolas, Microsoft YaHei" TextChanged="LogChanged" Margin="0,6,0,0"/>
</Grid>
<DockPanel Grid.Row="3" Margin="0,10,0,0"><ProgressBar DockPanel.Dock="Right" Width="180" Height="5" Value="{Binding Progress}" Foreground="{StaticResource Accent}" Background="{StaticResource Line}"/><TextBlock Text="{Binding Status}" TextTrimming="CharacterEllipsis" Margin="0,0,15,0"/></DockPanel>
</Grid>
</ScrollViewer>
</UserControl>

View File

@ -1,80 +0,0 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.VVMs.SopPage;
namespace SopHelper.Training;
[NavigationPage(ViewName = nameof(TrainingPage), DisplayName = "零件标注与训练", Index = 1)]
public partial class TrainingPage : UserControl
{
private readonly MainViewModel _model;
private readonly SopPageViewModel? _sop;
private CameraWindow? _cameraWindow;
private Window? _host;
private bool _closing;
private bool _closedSafely;
public TrainingPage(MainViewModel model, SopPageViewModel? sop)
{
InitializeComponent();
_model = model; _sop = sop; DataContext = model;
Canvas.BoxDrawn += model.DrawBox;
model.ReadApiKey = () => ApiKey.Password;
Loaded += (_, _) =>
{
// Keep this handler when navigating away: background work still belongs to the shell.
if (_host != null || Window.GetWindow(this) is not { } host) return;
_host = host; host.Closing += HostClosing;
};
PreviewKeyDown += (_, e) =>
{
if (model.IsBusy || Keyboard.FocusedElement is TextBoxBase or PasswordBox) return;
if (e.Key == Key.Left) { model.PreviousCommand.Execute(); e.Handled = true; }
else if (e.Key == Key.Right) { model.NextCommand.Execute(); e.Handled = true; }
else if (e.Key == Key.Enter && model.SelectedFrame?.Box != null)
{
model.ApproveCommand.Execute(); model.NextCommand.Execute(); e.Handled = true;
}
};
}
private void OpenCameraClicked(object sender, RoutedEventArgs e)
{
if (_sop is { CanSelectCamera: false } || _sop is { IsConnected: true })
{
_model.Status = "请先停止 SOP 采集并等待相机操作完成,再打开录像";
return;
}
_cameraWindow = new CameraWindow(new CameraViewModel(new CameraService(), _model.Root)) { Owner = Window.GetWindow(this) };
// A modal capture session prevents SOP or recipe calibration from opening the same device.
try { _cameraWindow.ShowDialog(); }
finally { _cameraWindow = null; }
}
public async Task ShutdownAsync()
{
await _model.StopAsync();
if (_cameraWindow != null) await _cameraWindow.Model.ShutdownAsync();
}
private async void HostClosing(object? sender, CancelEventArgs e)
{
if (_closedSafely) return;
e.Cancel = true;
if (_closing) return;
_closing = true;
_host!.IsEnabled = false;
try { await ShutdownAsync(); }
catch (Exception error) { MessageBox.Show(_host, "关闭训练任务时出错:" + error.Message, "SopHelper"); }
_closedSafely = true;
// Even an idle workspace can complete synchronously inside the first Closing event.
_ = Dispatcher.BeginInvoke(() => _host.Close());
}
private void LogChanged(object sender, TextChangedEventArgs e) => ((TextBox)sender).ScrollToEnd();
}

View File

@ -1,77 +0,0 @@
<Window x:Class="SopHelper.VVMs.MainWindow.MainWindow"
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"
Title="{Binding Title}"
Height="720" Width="1180"
MinHeight="560" MinWidth="900"
WindowState="Maximized"
Background="{StaticResource Bg}"
WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/SopHelper;component/Assets/BellwetherLogo.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- 标题栏 -->
<Border Grid.ColumnSpan="2" HorizontalAlignment="Left"
Width="202" Height="72" Margin="2,2,2,10"
Background="Transparent" BorderThickness="0" CornerRadius="4" Padding="6">
<Image Source="{StaticResource BellwetherLogo}" Stretch="Uniform"
AutomationProperties.Name="贝沃思 BELLWETHER" />
</Border>
<!-- 侧导航 -->
<Border Grid.Row="1" Margin="0,0,10,0">
<ListBox ItemsSource="{Binding Navigation.Pages}"
SelectedIndex="{Binding Navigation.SelectedIndex, Mode=TwoWay}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="12,10" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="bd" Background="Transparent" Padding="{TemplateBinding Padding}" CornerRadius="5">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="#22FFFFFF" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayName}" FontSize="14" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<!-- 内容区(导航宿主) -->
<ContentControl Grid.Row="1" Grid.Column="1"
prism:RegionManager.RegionName="ContentRegion" />
</Grid>
</Window>

View File

@ -1,17 +0,0 @@
using System.Windows;
namespace SopHelper.VVMs.MainWindow;
/// <summary>
/// 主窗口(shell:侧导航 + 内容区)
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// 主窗口
/// </summary>
public MainWindow()
{
InitializeComponent();
}
}

View File

@ -1,39 +0,0 @@
using Prism.Commands;
using Prism.Mvvm;
using SopHelper.Models;
namespace SopHelper.VVMs.MainWindow;
/// <summary>
/// Main窗口视图模型
/// </summary>
public class MainWindowViewModel : BindableBase
{
private readonly NavigationModel _navigation;
/// <summary>
/// Main窗口视图模型
/// </summary>
public MainWindowViewModel(NavigationModel navigation)
{
_navigation = navigation;
}
private string _title = "SopHelper";
/// <summary>
/// 标题
/// </summary>
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
/// <summary>
/// 导航模型(侧栏绑定)
/// </summary>
public NavigationModel Navigation => _navigation;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,607 +0,0 @@
<UserControl x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor"
prism:ViewModelLocator.AutoWireViewModel="True"
Background="{StaticResource Bg}">
<prism:Dialog.WindowStyle>
<Style TargetType="Window">
<Setter Property="Width" Value="1040" />
<Setter Property="Height" Value="760" />
<Setter Property="MinWidth" Value="1040" />
<Setter Property="MinHeight" Value="760" />
<Setter Property="SizeToContent" Value="Manual" />
<Setter Property="ResizeMode" Value="CanResize" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
</Style>
</prism:Dialog.WindowStyle>
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<!-- 一行字段:标签 + 控件 -->
<Style x:Key="Row" TargetType="Grid">
<Setter Property="Margin" Value="0,0,0,6" />
</Style>
<!-- 列表里的删除按钮 -->
<Style x:Key="Mini" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Padding" Value="8,3" />
<Setter Property="FontSize" Value="12" />
</Style>
<DataTemplate DataType="{x:Type ed:TextItem}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="1" Margin="6,0,0,0" Style="{StaticResource Mini}"
Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type ed:ViolationRuleNode}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding DataContext.Recipe.ViolationTypes, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Type}" />
<TextBox Grid.Column="1" Margin="6,0,0,0" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Column="2" Margin="6,0,0,0" Text="{Binding Severity}" />
<Button Grid.Column="3" Margin="6,0,0,0" Style="{StaticResource Mini}"
Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<!-- 步骤列表项 -->
<DataTemplate x:Key="StepRow" DataType="{x:Type ed:StepNode}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock>
<Run Text="{Binding Id}" Foreground="{StaticResource Accent}" /><Run Text=" " /><Run Text="{Binding Name}" />
</TextBlock>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="↑" Style="{StaticResource Mini}" Margin="2,0,0,0"
Command="{Binding DataContext.Recipe.MoveStepUpCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
<Button Content="↓" Style="{StaticResource Mini}" Margin="2,0,0,0"
Command="{Binding DataContext.Recipe.MoveStepDownCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
<Button Content="×" Style="{StaticResource Mini}" Margin="2,0,0,0" Foreground="{StaticResource Ng}"
Command="{Binding DataContext.Recipe.RemoveStepCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</DataTemplate>
<!-- 区域列表项 -->
<DataTemplate x:Key="RegionRow" DataType="{x:Type ed:RegionNode}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Rectangle Width="10" Height="10" Fill="{Binding Brush}" VerticalAlignment="Center" />
<TextBlock Margin="6,0,0,0">
<Run Text="{Binding Key}" Foreground="{StaticResource Accent}" /><Run Text=" " /><Run Text="{Binding Name}" />
</TextBlock>
</StackPanel>
<Button Grid.Column="1" Content="×" Style="{StaticResource Mini}" Foreground="{StaticResource Ng}"
Command="{Binding DataContext.Recipe.RemoveRegionCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<!-- 列表用普通条目模板(全局 ListBox 样式是给导航用的,这里要单列可选项) -->
<Style x:Key="Pick" TargetType="ListBox">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
</Style>
<Style x:Key="PickItem" TargetType="ListBoxItem">
<Setter Property="Padding" Value="8,6" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="bd" Background="Transparent" Padding="{TemplateBinding Padding}" CornerRadius="4">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="#22FFFFFF" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bd" Property="Background" Value="#3300B8D4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- ============ 头部:文件 + 配方名 ============ -->
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="{Binding Title}" Style="{StaticResource Title}" />
<TextBlock Text="文件名" Style="{StaticResource Field}" Margin="24,0,8,0" />
<TextBox Width="150" IsEnabled="{Binding Recipe.CanEditFileName}"
ToolTip="只有新建时能改——SOP 页是按文件名选配方的"
Text="{Binding Recipe.FileName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="配方名" Style="{StaticResource Field}" Margin="16,0,8,0" />
<TextBox Width="170" Text="{Binding Recipe.Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="版本" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Width="60" Text="{Binding Recipe.Version, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
<TabControl Grid.Row="1">
<!-- ==================== 步骤 ==================== -->
<TabItem Header="步骤">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="270" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DockPanel>
<Button DockPanel.Dock="Bottom" Content="加步骤" Margin="0,8,0,0" Padding="0,6"
Command="{Binding Recipe.AddStepCommand}" />
<ListBox Style="{StaticResource Pick}" ItemContainerStyle="{StaticResource PickItem}"
ItemTemplate="{StaticResource StepRow}"
ItemsSource="{Binding Recipe.Steps}"
SelectedItem="{Binding Recipe.SelectedStep}" />
</DockPanel>
<ScrollViewer Grid.Column="1" Margin="12,0,0,0" VerticalScrollBarVisibility="Auto"
DataContext="{Binding Recipe.SelectedStep}">
<StackPanel>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="步骤号" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Id}" />
<TextBlock Grid.Column="2" Text="超时秒" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Timeout}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="步骤名" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Grid.Column="2" Text="节拍毫秒" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding StandardDurationMs}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="说明" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<!-- 判定条件 -->
<TextBlock Text="判定条件" Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6" />
<StackPanel>
<TextBlock Text="请先选择判定方法;等待后完成请选择 time_elapsed">
<TextBlock.Style>
<Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Detection}" Value="{x:Null}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Detection.Method}" Value="">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<Grid Style="{StaticResource Row}" Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="方法" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.Methods, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Method}" />
<TextBlock Grid.Column="2" Text="目标类别" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Detection.TargetObject, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="主区域" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Region}" />
<TextBlock Grid.Column="2" Text="起点区域" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<ComboBox Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.FromRegion}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="终点区域" Style="{StaticResource Field}" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.ToRegion}" />
<TextBlock Grid.Column="2" Text="手" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<ComboBox Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.Hands, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Detection.Hand}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="容差像素" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Detection.Tolerance}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Detection.MinConfidence}" />
<TextBlock Grid.Column="2" Text="稳定帧" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding Detection.StableFrames}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="计时毫秒" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Detection.DurationMs}" HorizontalAlignment="Left" Width="120" />
</Grid>
<TextBlock Text="time_elapsed / hand_move 豁免稳定帧门控(自带时序或瞬时语义)"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
</StackPanel>
<!-- 必在物料 / 完成时必须存在 -->
<DockPanel Margin="0,10,0,6">
<Button DockPanel.Dock="Right" Content="加必留物品" Style="{StaticResource Mini}"
Command="{Binding MustKeep.AddCommand}" />
<TextBlock Style="{StaticResource Title}" FontSize="13"
Text="{Binding MustKeep.Title}" />
</DockPanel>
<ItemsControl ItemsSource="{Binding MustKeep.Items}" />
<DockPanel Margin="0,10,0,6">
<Button DockPanel.Dock="Right" Content="加完成必需物品" Style="{StaticResource Mini}"
Command="{Binding RequiredObjects.AddCommand}" />
<TextBlock Style="{StaticResource Title}" FontSize="13"
Text="{Binding RequiredObjects.Title}" />
</DockPanel>
<ItemsControl ItemsSource="{Binding RequiredObjects.Items}" />
<DockPanel Margin="0,10,0,6">
<Button DockPanel.Dock="Right" Content="加违规规则" Style="{StaticResource Mini}"
Command="{Binding ViolationRules.AddCommand}" />
<TextBlock Style="{StaticResource Title}" FontSize="13"
Text="{Binding ViolationRules.Title}" />
</DockPanel>
<ItemsControl ItemsSource="{Binding ViolationRules.Items}" />
</StackPanel>
</ScrollViewer>
</Grid>
</TabItem>
<!-- ==================== 区域 ==================== -->
<TabItem Header="区域">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="230" />
</Grid.ColumnDefinitions>
<DockPanel>
<Button DockPanel.Dock="Bottom" Content="加区域" Margin="0,8,0,0" Padding="0,6"
Command="{Binding Recipe.AddRegionCommand}" />
<ListBox Style="{StaticResource Pick}" ItemContainerStyle="{StaticResource PickItem}"
ItemTemplate="{StaticResource RegionRow}"
ItemsSource="{Binding Recipe.Regions}"
SelectedItem="{Binding Recipe.SelectedRegion}" />
</DockPanel>
<Grid Grid.Column="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" MinHeight="210" />
</Grid.RowDefinitions>
<WrapPanel Margin="0,0,0,6">
<Button Content="从相机取图" Style="{StaticResource Mini}" Command="{Binding CaptureImageCommand}" />
<Button Content="打开图片" Style="{StaticResource Mini}" Command="{Binding OpenImageCommand}" Margin="8,0,0,0" />
</WrapPanel>
<TextBlock Grid.Row="1" Text="选中左侧区域,再在图上拖动画框" TextWrapping="Wrap"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
<TextBlock Grid.Row="2" Text="{Binding PreviewStatus}" TextWrapping="Wrap"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
<Border Grid.Row="3" Padding="0" CornerRadius="4" ClipToBounds="True">
<ed:RegionCanvas Image="{Binding PreviewImage}" Regions="{Binding Recipe.Regions}"
SelectedRegion="{Binding Recipe.SelectedRegion, Mode=TwoWay}" />
</Border>
</Grid>
<ScrollViewer x:Name="RegionParameters" Grid.Column="2" VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<StackPanel DataContext="{Binding Recipe.SelectedRegion}">
<TextBlock Text="区域参数" Style="{StaticResource Title}" FontSize="13" Margin="0,0,0,10" />
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="键名" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Key, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="显示名" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="X1" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding X1, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Y1" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Y1, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="X2" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding X2, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Y2" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Y2, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="颜色" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Color, UpdateSourceTrigger=PropertyChanged}" />
<Rectangle Grid.Column="2" Width="18" Height="18" Fill="{Binding Brush}" Margin="6,0,0,0"
VerticalAlignment="Center" />
</Grid>
<TextBlock Text="说明" Foreground="{StaticResource FgDim}" Margin="0,4,0,6" />
<TextBox Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap"
AcceptsReturn="True" Height="72" VerticalScrollBarVisibility="Auto" />
<TextBlock Text="坐标使用原图像素;画框更新右侧数值,也可手动微调。" TextWrapping="Wrap"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,12,0,0" />
<TextBlock Text="改键名会同步更新所有步骤里对它的引用" TextWrapping="Wrap"
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,8,0,0" />
</StackPanel>
</ScrollViewer>
</Grid>
</TabItem>
<!-- ==================== 全局设置 ==================== -->
<TabItem Header="全局设置">
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding ConfidenceThreshold}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="稳定帧" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding StableFrames}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="命中容差" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding PositionTolerance}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="抽帧" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
<TextBox Grid.Column="3" Text="{Binding FrameStride}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="复位延时" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding ResetDelaySec}" HorizontalAlignment="Left" Width="120" />
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<CheckBox Content="超时违规" IsChecked="{Binding EnableTimeoutDetection}" Margin="0,0,20,0" />
<CheckBox Content="完成后自动复位" IsChecked="{Binding AutoResetOnComplete}" />
</StackPanel>
</StackPanel>
</TabItem>
<!-- ==================== 检测模型 ==================== -->
<TabItem Header="检测模型">
<StackPanel x:Name="ModelSettings" Margin="10" DataContext="{Binding Recipe}">
<CheckBox Content="使用检测模型(object_* 与 hand_near_object / person_present 依赖它)"
IsChecked="{Binding HasModel}" Margin="0,0,0,10" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
<TextBox x:Name="CameraExposureInput" Width="120"
Text="{Binding Settings.ExposureTimeUs, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"
ToolTip="海康相机曝光时间,10000 为 10 毫秒;留空保留相机设置。保存配方后保留,区域取图和 SOP 启动前应用。" />
</StackPanel>
<StackPanel Visibility="{Binding DataContext.HasModel, ElementName=ModelSettings, Converter={StaticResource BoolToVis}}" DataContext="{Binding Model}">
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="模型路径" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding Path, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="2" Content="选择模型…" Margin="8,0,0,0" Style="{StaticResource Mini}"
Command="{Binding DataContext.BrowseModelCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</Grid>
<Grid Style="{StaticResource Row}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="输入尺寸" Style="{StaticResource Field}" />
<TextBox Grid.Column="1" Text="{Binding InputSize}" HorizontalAlignment="Left" Width="120" />
</Grid>
<StackPanel DataContext="{Binding Classes}">
<TextBlock Style="{StaticResource Title}" FontSize="13" Margin="0,10,0,6" Text="{Binding Title}" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,6">
<Button Content="加类别" Style="{StaticResource Mini}" Command="{Binding AddCommand}" />
</StackPanel>
<ItemsControl ItemsSource="{Binding Items}" />
</StackPanel>
</StackPanel>
<TextBlock Margin="0,10,0,0" Foreground="{StaticResource FgDim}" TextWrapping="Wrap"
Text="可选择 .onnx 模型文件,或手填相对程序目录的路径;当前用的 yolo11n 是 AGPL-3.0 血统,量产前换掉(见 README)" />
</StackPanel>
</TabItem>
</TabControl>
<!-- ============ 底部:校验提醒 + 保存 ============ -->
<Grid Grid.Row="2" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="{Binding SaveStatus}" Foreground="{StaticResource Ok}" FontSize="12" />
<TextBlock Text="校验提醒(不阻止保存;现场常见先存草稿再补区域)" Foreground="{StaticResource FgDim}" FontSize="12" />
<ItemsControl ItemsSource="{Binding Warnings}" MaxHeight="66">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{StaticResource Ng}" FontSize="12" Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Bottom">
<Button Content="关闭" Command="{Binding CloseCommand}" Margin="0,0,8,0" />
<Button Content="保存" Command="{Binding SaveCommand}"
Background="{StaticResource Panel}" BorderBrush="{StaticResource Accent}" />
</StackPanel>
</Grid>
</Grid>
</UserControl>

View File

@ -1,15 +0,0 @@
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>
/// 配方编辑器(弹窗)。ViewModel 按命名约定自动绑定,见 App.ConfigureViewModelLocator。
/// </summary>
public partial class RecipeEditor : System.Windows.Controls.UserControl
{
/// <summary>
/// 配方编辑器
/// </summary>
public RecipeEditor()
{
InitializeComponent();
}
}

View File

@ -1,318 +0,0 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Camera;
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>
/// 配方编辑器(SOP 页「编辑」按钮弹出)。表单在 EditorNodes 那一侧,
/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
/// </summary>
public class RecipeEditorViewModel : BindableBase, IDialogAware
{
private RecipeNode _recipe = new();
private string _path = "";
private bool _isNew;
private Action<string>? _onSaved;
private readonly HashSet<EditorNode> _observedStepNodes = [];
private string _saveStatus = "";
public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
private BitmapSource? _previewImage;
private string _previewStatus = "选中一个区域后,在图像上拖动画框;Esc 取消本次绘制";
private bool _isCapturing;
private ICameraService? _camera;
private CameraInfo? _cameraInfo;
public BitmapSource? PreviewImage { get => _previewImage; private set => SetProperty(ref _previewImage, value); }
public string PreviewStatus { get => _previewStatus; private set => SetProperty(ref _previewStatus, value); }
public bool IsCapturing
{
get => _isCapturing;
private set
{
if (!SetProperty(ref _isCapturing, value)) return;
CaptureImageCommand.RaiseCanExecuteChanged();
OpenImageCommand.RaiseCanExecuteChanged();
BrowseModelCommand.RaiseCanExecuteChanged();
SaveCommand.RaiseCanExecuteChanged();
CloseCommand.RaiseCanExecuteChanged();
}
}
public DelegateCommand CaptureImageCommand { get; }
public DelegateCommand OpenImageCommand { get; }
public DelegateCommand BrowseModelCommand { get; }
/// <summary>当前编辑的配方目录(configs/sop)</summary>
private string _directory = "";
/// <inheritdoc />
public string Title => _isNew ? "新建配方" : $"编辑配方 - {FileNameText}";
/// <inheritdoc />
public DialogCloseListener RequestClose { get; } = new();
/// <summary>标题栏显示的文件名</summary>
public string FileNameText => string.IsNullOrEmpty(_path) ? $"{_recipe.FileName}.yaml(新建)" : Path.GetFileName(_path);
/// <summary>编辑中的配方</summary>
public RecipeNode Recipe
{
get { return _recipe; }
private set
{
if (!SetProperty(ref _recipe, value)) return;
RaisePropertyChanged(nameof(FileNameText));
RaisePropertyChanged(nameof(Title));
}
}
/// <summary>保存前的校验提醒(不阻止保存——现场常见"先存草稿再补区域")</summary>
public ObservableCollection<string> Warnings { get; } = [];
/// <summary>保存</summary>
public DelegateCommand SaveCommand { get; private set; } = null!;
/// <summary>关闭编辑器,未保存的修改不写入文件</summary>
public DelegateCommand CloseCommand { get; private set; } = null!;
/// <summary>
/// 配方编辑器
/// </summary>
public RecipeEditorViewModel()
{
SaveCommand = new DelegateCommand(Save, () => !IsCapturing);
CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel), () => !IsCapturing);
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
BrowseModelCommand = new DelegateCommand(BrowseModel, () => !IsCapturing);
}
/// <inheritdoc />
public void OnDialogOpened(IDialogParameters parameters)
{
_directory = parameters.GetValue<string>("directory") ?? "";
_path = parameters.GetValue<string>("path") ?? "";
_isNew = parameters.GetValue<bool>("new");
_onSaved = parameters.GetValue<Action<string>>("onSaved");
SaveStatus = "";
_camera = parameters.GetValue<ICameraService>("cameraService");
_cameraInfo = parameters.GetValue<CameraInfo>("cameraInfo");
PreviewImage = parameters.GetValue<BitmapSource>("preview");
CaptureImageCommand.RaiseCanExecuteChanged();
if (PreviewImage is not null) DescribeImage("最近一帧");
else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
var config = parameters.GetValue<SopConfig>("config") ?? new SopConfig();
// 新建时文件名还没定,用配方名兜底;已存在的文件名不可改(SOP 页按文件名选配方)
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
Recipe = RecipeNode.From(config, fileName, _isNew);
Recipe.Changed += RefreshWarnings;
RefreshWarnings();
}
/// <inheritdoc />
public bool CanCloseDialog() => !IsCapturing;
/// <inheritdoc />
public void OnDialogClosed()
{
Recipe.Changed -= RefreshWarnings;
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
_observedStepNodes.Clear();
_onSaved = null;
}
private void DescribeImage(string source) => PreviewStatus =
$"{source} · {PreviewImage!.PixelWidth} × {PreviewImage.PixelHeight} 像素;选中区域后拖动画框,Esc 取消";
private void OpenImage()
{
var dialog = new OpenFileDialog
{
Title = "选择区域标定图片(使用与相机相同分辨率的原图)",
Filter = "图像|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff|所有文件|*.*",
};
if (dialog.ShowDialog() != true) return;
try
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(dialog.FileName, UriKind.Absolute);
image.EndInit();
image.Freeze();
PreviewImage = image;
DescribeImage(Path.GetFileName(dialog.FileName));
}
catch (Exception ex) { PreviewStatus = "打开图片失败:" + ex.Message; }
}
private void BrowseModel()
{
if (Recipe.Model is null) return;
var dialog = new OpenFileDialog
{
Title = "选择 ONNX 检测模型",
Filter = "ONNX 模型 (*.onnx)|*.onnx",
DefaultExt = ".onnx",
CheckFileExists = true,
Multiselect = false,
InitialDirectory = AppContext.BaseDirectory,
};
try
{
if (!string.IsNullOrWhiteSpace(Recipe.Model.Path))
{
var currentPath = Path.GetFullPath(Recipe.Model.Path, AppContext.BaseDirectory);
var directory = Path.GetDirectoryName(currentPath);
if (Directory.Exists(directory)) dialog.InitialDirectory = directory;
if (File.Exists(currentPath)) dialog.FileName = Path.GetFileName(currentPath);
}
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
// 手填路径无效时,仍可从程序目录重新选择。
}
if (dialog.ShowDialog() != true) return;
Recipe.Model.Path = dialog.FileName;
RefreshWarnings();
}
private async Task CaptureImageAsync()
{
if (IsCapturing || _camera is null || _cameraInfo is null) return;
var camera = _camera;
IsCapturing = true;
PreviewStatus = "正在取图…";
var ready = new TaskCompletionSource<BitmapSource>(TaskCreationOptions.RunContinuationsAsynchronously);
void Receive(CameraFrame frame)
{
if (ready.Task.IsCompleted) return;
try
{
// 不保留相机 Mat;图像在采集线程复制并冻结后再交给 UI。
using var copy = frame.Bgr.Clone();
var bytes = new byte[checked(copy.Rows * copy.Cols * 3)];
Marshal.Copy(copy.Data, bytes, 0, bytes.Length);
var bitmap = BitmapSource.Create(copy.Cols, copy.Rows, 96, 96, PixelFormats.Bgr24,
null, bytes, copy.Cols * 3);
bitmap.Freeze();
ready.TrySetResult(bitmap);
}
catch (Exception ex) { ready.TrySetException(ex); }
}
try
{
if (!await camera.ConnectAsync(_cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
if (Recipe.Settings.ExposureTimeUs is { } exposure)
{
if (!double.IsFinite(exposure) || exposure <= 0)
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
await camera.SetExposureTimeAsync(exposure);
}
camera.FrameArrived += Receive;
if (!await camera.StartAsync()) throw new InvalidOperationException("启动采集失败");
PreviewImage = await ready.Task.WaitAsync(TimeSpan.FromSeconds(5));
DescribeImage(_cameraInfo.Name);
}
catch (Exception ex) { PreviewStatus = "取图失败:" + ex.Message; }
finally
{
camera.FrameArrived -= Receive;
try { await Task.Run(camera.Disconnect); }
catch (Exception ex) { PreviewStatus = "关闭相机失败:" + ex.Message; }
IsCapturing = false;
}
}
private void Save()
{
SaveStatus = "";
if (Recipe.Settings.ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
{
Warnings.Add("相机曝光必须大于 0(微秒),或留空保留相机设置");
return;
}
if (string.IsNullOrWhiteSpace(Recipe.Name))
{
Warnings.Add("配方名(sop.name)不能为空");
return;
}
var fileName = string.IsNullOrWhiteSpace(Recipe.FileName) ? Recipe.Name : Recipe.FileName;
// 只取文件名部分,别让人在这儿塞路径
fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName + ".yaml") : _path;
try
{
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
var saved = SopConfigLoader.Save(Recipe.ToConfig(), path);
_path = path;
_isNew = false;
Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
RaisePropertyChanged(nameof(FileNameText));
RaisePropertyChanged(nameof(Title));
Warnings.Clear();
foreach (var warning in saved.Warnings) Warnings.Add(warning);
SaveStatus = $"已保存 {Path.GetFileName(_path)}";
_onSaved?.Invoke(Path.GetFileName(_path));
}
catch (Exception ex)
{
// 写盘失败(文件被占用/只读)留给用户看,别让整个编辑器跟着炸
Warnings.Clear();
Warnings.Add("保存失败:" + ex.Message);
}
}
/// <summary>
/// 用当前编辑结果跑一遍加载器校验(就是"这一步永远不推进"那类问题)
/// </summary>
private void RefreshWarnings()
{
SaveStatus = "";
// 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。
var current = new HashSet<EditorNode>(Recipe.Steps);
foreach (var step in Recipe.Steps)
if (step.Detection is not null) current.Add(step.Detection);
foreach (var removed in _observedStepNodes.Except(current).ToArray())
{
removed.PropertyChanged -= StepChanged;
_observedStepNodes.Remove(removed);
}
foreach (var added in current.Except(_observedStepNodes))
{
added.PropertyChanged += StepChanged;
_observedStepNodes.Add(added);
}
Warnings.Clear();
var config = Recipe.ToConfig();
SopConfigLoader.Validate(config);
foreach (var warning in config.Warnings) Warnings.Add(warning);
}
private void StepChanged(object? sender, PropertyChangedEventArgs e) => RefreshWarnings();
}

View File

@ -1,177 +0,0 @@
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>图像按比例居中显示;拖动坐标映射到原图像素,留白不参与标定。</summary>
public sealed class RegionCanvas : FrameworkElement
{
public static readonly DependencyProperty ImageProperty = DependencyProperty.Register(
nameof(Image), typeof(BitmapSource), typeof(RegionCanvas),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, CancelOnChange));
public static readonly DependencyProperty RegionsProperty = DependencyProperty.Register(
nameof(Regions), typeof(ObservableCollection<RegionNode>), typeof(RegionCanvas),
new FrameworkPropertyMetadata(null, RegionsChanged));
public static readonly DependencyProperty SelectedRegionProperty = DependencyProperty.Register(
nameof(SelectedRegion), typeof(RegionNode), typeof(RegionCanvas),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, CancelOnChange));
public BitmapSource? Image { get => (BitmapSource?)GetValue(ImageProperty); set => SetValue(ImageProperty, value); }
public ObservableCollection<RegionNode>? Regions { get => (ObservableCollection<RegionNode>?)GetValue(RegionsProperty); set => SetValue(RegionsProperty, value); }
public RegionNode? SelectedRegion { get => (RegionNode?)GetValue(SelectedRegionProperty); set => SetValue(SelectedRegionProperty, value); }
private readonly HashSet<RegionNode> _observed = [];
private Point? _start;
private Point _end;
private RegionNode? _drawingRegion;
public RegionCanvas()
{
Focusable = true;
Cursor = Cursors.Cross;
Unloaded += (_, _) => CancelDrag();
}
public static Rect FitImage(Size viewport, Size image)
{
if (viewport.Width <= 0 || viewport.Height <= 0 || image.Width <= 0 || image.Height <= 0) return Rect.Empty;
var scale = Math.Min(viewport.Width / image.Width, viewport.Height / image.Height);
var size = new Size(image.Width * scale, image.Height * scale);
return new Rect(new Point((viewport.Width - size.Width) / 2, (viewport.Height - size.Height) / 2), size);
}
public static Point ToImage(Point point, Rect display, Size image) => new(
Math.Clamp((point.X - display.X) * image.Width / display.Width, 0, image.Width),
Math.Clamp((point.Y - display.Y) * image.Height / display.Height, 0, image.Height));
public static Int32Rect PixelBounds(Point first, Point last, Size image)
{
var x1 = (int)Math.Clamp(Math.Floor(Math.Min(first.X, last.X)), 0, image.Width);
var y1 = (int)Math.Clamp(Math.Floor(Math.Min(first.Y, last.Y)), 0, image.Height);
var x2 = (int)Math.Clamp(Math.Ceiling(Math.Max(first.X, last.X)), 0, image.Width);
var y2 = (int)Math.Clamp(Math.Ceiling(Math.Max(first.Y, last.Y)), 0, image.Height);
return new Int32Rect(x1, y1, x2 - x1, y2 - y1);
}
protected override void OnRender(DrawingContext dc)
{
dc.DrawRectangle(new SolidColorBrush(Color.FromRgb(10, 16, 22)), null, new Rect(RenderSize));
if (Image is null)
{
var text = new FormattedText("从相机取图,或打开一张图片后画框", CultureInfo.CurrentCulture,
FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), 13, Brushes.LightGray,
VisualTreeHelper.GetDpi(this).PixelsPerDip);
dc.DrawText(text, new Point(Math.Max(8, (ActualWidth - text.Width) / 2), Math.Max(8, ActualHeight / 2 - text.Height / 2)));
return;
}
var size = new Size(Image.PixelWidth, Image.PixelHeight);
var display = FitImage(RenderSize, size);
if (display.IsEmpty) return;
dc.DrawImage(Image, display);
var scale = display.Width / size.Width;
dc.PushClip(new RectangleGeometry(display));
dc.PushTransform(new MatrixTransform(scale, 0, 0, scale, display.X, display.Y));
foreach (var region in Regions ?? [])
{
if (region.X2 <= region.X1 || region.Y2 <= region.Y1) continue;
var rect = new Rect(region.X1, region.Y1, region.X2 - region.X1, region.Y2 - region.Y1);
var selected = ReferenceEquals(region, SelectedRegion);
var pen = new Pen(region.Brush, (selected ? 3 : 1.5) / scale);
if (selected) dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(35, 0, 184, 212)), null, rect);
dc.DrawRectangle(null, pen, rect);
var label = new FormattedText(string.IsNullOrWhiteSpace(region.Name) ? region.Key : region.Name,
CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"),
12 / scale, region.Brush, VisualTreeHelper.GetDpi(this).PixelsPerDip);
var origin = new Point(Math.Max(0, rect.X), Math.Max(0, rect.Y - label.Height));
dc.DrawRectangle(Brushes.Black, null, new Rect(origin, new Size(label.Width, label.Height)));
dc.DrawText(label, origin);
}
if (_start is Point start)
{
var pen = new Pen(Brushes.Yellow, 2 / scale) { DashStyle = DashStyles.Dash };
dc.DrawRectangle(null, pen, new Rect(start, _end));
}
dc.Pop();
dc.Pop();
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
if (Image is null || SelectedRegion is null) return;
var display = FitImage(RenderSize, new Size(Image.PixelWidth, Image.PixelHeight));
var point = e.GetPosition(this);
if (display.IsEmpty || !display.Contains(point)) return;
Focus();
if (!CaptureMouse()) return;
_drawingRegion = SelectedRegion;
_start = _end = ToImage(point, display, new Size(Image.PixelWidth, Image.PixelHeight));
InvalidateVisual();
e.Handled = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (_start is null || Image is null) return;
_end = ToImage(e.GetPosition(this), FitImage(RenderSize, new Size(Image.PixelWidth, Image.PixelHeight)),
new Size(Image.PixelWidth, Image.PixelHeight));
InvalidateVisual();
e.Handled = true;
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
if (_start is not Point start || Image is null) return;
var size = new Size(Image.PixelWidth, Image.PixelHeight);
var display = FitImage(RenderSize, size);
var end = ToImage(e.GetPosition(this), display, size);
var bounds = PixelBounds(start, end, size);
// 单击不改坐标;拖出图像时按图像边界截取。
if (bounds.Width * display.Width / size.Width >= 4 && bounds.Height * display.Height / size.Height >= 4 &&
ReferenceEquals(_drawingRegion, SelectedRegion))
_drawingRegion?.SetBounds(bounds);
CancelDrag();
e.Handled = true;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Escape && _start is not null) { CancelDrag(); e.Handled = true; }
else base.OnKeyDown(e);
}
protected override void OnLostMouseCapture(MouseEventArgs e) { base.OnLostMouseCapture(e); CancelDrag(); }
private void CancelDrag()
{
_start = null;
_drawingRegion = null;
if (IsMouseCaptured) ReleaseMouseCapture();
InvalidateVisual();
}
private static void CancelOnChange(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((RegionCanvas)d).CancelDrag();
private static void RegionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var canvas = (RegionCanvas)d;
if (e.OldValue is ObservableCollection<RegionNode> old) old.CollectionChanged -= canvas.CollectionChanged;
if (e.NewValue is ObservableCollection<RegionNode> current) current.CollectionChanged += canvas.CollectionChanged;
canvas.ObserveRegions();
}
private void CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { CancelDrag(); ObserveRegions(); }
private void ObserveRegions()
{
foreach (var node in _observed) node.PropertyChanged -= NodeChanged;
_observed.Clear();
foreach (var node in Regions ?? []) { _observed.Add(node); node.PropertyChanged += NodeChanged; }
InvalidateVisual();
}
private void NodeChanged(object? sender, PropertyChangedEventArgs e) => InvalidateVisual();
}

View File

@ -1,65 +0,0 @@
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using SopHelper.Engine.Common;
namespace SopHelper.VVMs.SopPage;
/// <summary>按原图像素绘制目标框与标签,与视频一起缩放。</summary>
public sealed class DetectionOverlay : FrameworkElement
{
public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
nameof(Result), typeof(FrameResult), typeof(DetectionOverlay),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public FrameResult? Result
{
get => (FrameResult?)GetValue(ResultProperty);
set => SetValue(ResultProperty, value);
}
protected override void OnRender(DrawingContext drawing)
{
base.OnRender(drawing);
var result = Result;
if (result is null || result.Size.W <= 0 || result.Size.H <= 0 ||
ActualWidth <= 0 || ActualHeight <= 0) return;
drawing.PushClip(new RectangleGeometry(new Rect(RenderSize)));
drawing.PushTransform(new ScaleTransform(ActualWidth / result.Size.W, ActualHeight / result.Size.H));
var imageBounds = new Rect(0, 0, result.Size.W, result.Size.H);
var unit = Math.Max(result.Size.W, result.Size.H) / 700.0;
var pen = new Pen(Brushes.Orange, 2 * unit);
var background = new SolidColorBrush(Color.FromArgb(220, 12, 18, 24));
var typeface = new Typeface("Microsoft YaHei");
var padding = 3 * unit;
foreach (var detection in result.Detections)
{
var box = detection.Rect;
if (!float.IsFinite(box.X) || !float.IsFinite(box.Y) ||
!float.IsFinite(box.Right) || !float.IsFinite(box.Bottom) ||
!float.IsFinite(detection.Confidence) || box.W <= 0 || box.H <= 0) continue;
var bounds = Rect.Intersect(imageBounds, new Rect(box.X, box.Y, box.W, box.H));
if (bounds.IsEmpty || bounds.Width <= 0 || bounds.Height <= 0) continue;
drawing.DrawRectangle(null, pen, bounds);
var label = new FormattedText($"{detection.Label} {detection.Confidence:P0}",
CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface,
12 * unit, Brushes.White, VisualTreeHelper.GetDpi(this).PixelsPerDip)
{
MaxTextWidth = Math.Max(1, imageBounds.Width - 2 * padding),
MaxLineCount = 1,
Trimming = TextTrimming.CharacterEllipsis,
};
var labelSize = new Size(label.Width + 2 * padding, label.Height + 2 * padding);
var left = Math.Clamp(bounds.Left, 0, Math.Max(0, imageBounds.Width - labelSize.Width));
var top = bounds.Top >= labelSize.Height ? bounds.Top - labelSize.Height : bounds.Top;
top = Math.Clamp(top, 0, Math.Max(0, imageBounds.Height - labelSize.Height));
drawing.DrawRectangle(background, null, new Rect(new Point(left, top), labelSize));
drawing.DrawText(label, new Point(left + padding, top + padding));
}
drawing.Pop();
drawing.Pop();
}
}

View File

@ -1,66 +0,0 @@
using System.Windows;
using System.Windows.Media;
using SopHelper.Engine.Common;
namespace SopHelper.VVMs.SopPage;
/// <summary>按原图坐标绘制手部结果,与视频、ROI 一起缩放,不修改用于检测的图像。</summary>
public sealed class HandOverlay : FrameworkElement
{
private static readonly (int From, int To)[] Bones =
[
(0, 1), (1, 2), (2, 3), (3, 4),
(0, 5), (5, 6), (6, 7), (7, 8),
(5, 9), (9, 10), (10, 11), (11, 12),
(9, 13), (13, 14), (14, 15), (15, 16),
(13, 17), (0, 17), (17, 18), (18, 19), (19, 20),
];
public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
nameof(Result), typeof(FrameResult), typeof(HandOverlay),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public FrameResult? Result
{
get => (FrameResult?)GetValue(ResultProperty);
set => SetValue(ResultProperty, value);
}
protected override void OnRender(DrawingContext drawing)
{
base.OnRender(drawing);
var result = Result;
if (result is null || result.Size.W <= 0 || result.Size.H <= 0 ||
ActualWidth <= 0 || ActualHeight <= 0) return;
drawing.PushClip(new RectangleGeometry(new Rect(RenderSize)));
drawing.PushTransform(new ScaleTransform(ActualWidth / result.Size.W, ActualHeight / result.Size.H));
// 按图像尺寸设置线宽,海康高分辨率图缩小预览后仍可看清。
var unit = Math.Max(result.Size.W, result.Size.H) / 700.0;
foreach (var hand in result.Hands)
{
var brush = hand.HandType switch
{
HandType.Left => Brushes.LimeGreen,
HandType.Right => Brushes.DeepSkyBlue,
_ => Brushes.Gray,
};
var pen = new Pen(brush, unit * 2);
var points = hand.Keypoints
.Where(p => p.Index is >= 0 and <= 20 && p.Confidence > 0 &&
float.IsFinite(p.X) && float.IsFinite(p.Y))
.GroupBy(p => p.Index).ToDictionary(g => g.Key, g => g.First());
foreach (var (from, to) in Bones)
if (points.TryGetValue(from, out var start) && points.TryGetValue(to, out var end))
drawing.DrawLine(pen, new Point(start.X, start.Y), new Point(end.X, end.Y));
foreach (var point in points.Values)
drawing.DrawEllipse(Brushes.Yellow, null, new Point(point.X, point.Y), unit * 3, unit * 3);
}
drawing.Pop();
drawing.Pop();
}
}

View File

@ -1,282 +0,0 @@
<UserControl x:Class="SopHelper.VVMs.SopPage.SopPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:local="clr-namespace:SopHelper.VVMs.SopPage"
prism:ViewModelLocator.AutoWireViewModel="True"
Background="{StaticResource Bg}">
<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>
<local:DetectionOverlay Result="{Binding HandResult}" IsHitTestVisible="False" />
<local:HandOverlay Result="{Binding HandResult}" IsHitTestVisible="False" />
</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}"
IsEnabled="{Binding CanSelectCamera}"
ToolTip="支持 UVC 和海康 GigE/USB 工业相机"
SelectedItem="{Binding SelectedCamera}">
<!-- 实测 DisplayMemberPath 在运行时没生效(显示 ToString()),显式模板最稳 -->
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<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" />
<ColumnDefinition Width="Auto" />
<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 EditRecipeCommand}" />
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4"
Command="{Binding NewRecipeCommand}" />
<Button Grid.Column="4" 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="{Binding ConnectionText}" Margin="6,0,0,0" Foreground="{StaticResource FgDim}" />
</StackPanel>
</Grid>
</Grid>
</UserControl>

View File

@ -1,18 +0,0 @@
using SopHelper.Core.Prism;
namespace SopHelper.VVMs.SopPage;
/// <summary>
/// SOP 主页(画面 + 步骤卡 + 参数)
/// </summary>
[NavigationPage(ViewName = "SopPage", DisplayName = "SOP 辅助", Index = 0)]
public partial class SopPage : System.Windows.Controls.UserControl
{
/// <summary>
/// SOP 主页
/// </summary>
public SopPage()
{
InitializeComponent();
}
}

View File

@ -1,845 +0,0 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using Prism.Commands;
using Prism.Dialogs;
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 主页视图模型:相机 → 推理管线 → SOP 引擎,界面只订阅事件。
/// </summary>
public class SopPageViewModel : ViewModelBase
{
private const int MaxLogLines = 300;
private const int MaxTopViolations = 3;
/// <summary>配方目录(相对程序目录)</summary>
private static string RecipeDirectory => Path.Combine(AppContext.BaseDirectory, "configs", "sop");
private static string LastCameraPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
/// <summary>配方编辑器弹窗的注册名(见 App.RegisterTypes)</summary>
private const string EditorDialogName = "RecipeEditorDialog";
private readonly ICameraService _camera;
private readonly DetectionPipeline _pipeline;
private readonly SopEngine _engine;
private readonly IDialogService _dialogs;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _renderTimer;
/// <summary>采集线程写、UI 线程取最新帧</summary>
private readonly object _frameLock = new();
private Mat? _pending;
private bool _destroyed;
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
private FrameResult? _lastFrame;
private FrameResult? _handResult;
private WriteableBitmap? _bitmap;
private long _frameCount;
private long _lastTickCount;
private CameraInfo? _selectedCamera;
private CameraInfo? _lastUsedCamera;
private string? _selectedRecipe;
private ImageSource? _frame;
private string _statusText = "就绪";
private string _fpsText = "—";
private string _inferenceText = "—";
private bool _isRunning;
private bool _isConnected;
private bool _isCameraBusy;
private double _frameWidth;
private double _frameHeight;
private double _confidence = 0.6;
private int _frameStride = 2;
/// <summary>
/// SOP 主页视图模型
/// </summary>
public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine, IDialogService dialogs)
{
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() =>
{
IsConnected = on;
if (!on && IsRunning)
{
IsRunning = false;
StatusText = "相机已断开";
RaiseCommands();
}
});
_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(), () => CanSelectCamera);
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning && !_isCameraBusy);
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning && !_isCameraBusy);
StatusText = "选择相机和配方,点开始";
LoadLastCamera();
_ = RefreshCamerasAsync();
}
/// <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
{
if (!SetProperty(ref _selectedCamera, value)) return;
RaiseCommands(); // 实测:不刷新会导致"开始/停止"一直灰着,选了相机也点不动
}
}
/// <summary>选中配方</summary>
public string? SelectedRecipe
{
get { return _selectedRecipe; }
set
{
if (!SetProperty(ref _selectedRecipe, value)) return;
RaiseCommands();
}
}
/// <summary>画面</summary>
public ImageSource? Frame
{
get { return _frame; }
set { SetProperty(ref _frame, value); }
}
/// <summary>最近一次推理结果,供图像上的手部与目标检测绘制层使用。</summary>
public FrameResult? HandResult
{
get => _handResult;
private set => SetProperty(ref _handResult, 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
{
if (!SetProperty(ref _isRunning, value)) return;
if (!value) HandResult = null;
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
}
}
/// <summary>连接、枚举、采集期间不切换设备。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
/// <summary>相机是否已连接</summary>
public bool IsConnected
{
get { return _isConnected; }
set
{
if (!SetProperty(ref _isConnected, value)) return;
RaisePropertyChanged(nameof(ConnectionText));
}
}
/// <summary>右下角连接文字(实测静态文字不反映状态,改成绑定)</summary>
public string ConnectionText => IsConnected ? "相机已连接" : "相机未连接";
/// <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!;
/// <summary>编辑当前选中的配方(弹窗)</summary>
public DelegateCommand EditRecipeCommand { get; private set; } = null!;
/// <summary>新建配方(弹窗)</summary>
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
private bool CanStart() => !_isCameraBusy && (SelectedCamera is not null || IsRunning);
private void SetCameraBusy(bool busy)
{
_isCameraBusy = busy;
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
}
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
/// <summary>
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
/// 绑定上去的按钮不会因属性变化自动亮起来(实测:选了相机"开始/停止"仍灰着)。
/// </summary>
private void RaiseCommands()
{
// 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
RefreshCamerasCommand?.RaiseCanExecuteChanged();
StartStopCommand?.RaiseCanExecuteChanged();
TogglePauseCommand?.RaiseCanExecuteChanged();
ResetCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
}
/// <summary>
/// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期
/// </summary>
private void OnCameraFrame(CameraFrame frame)
{
lock (_frameLock)
{
if (_destroyed) return;
var clone = frame.Bgr.Clone();
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();
_camera.FrameArrived -= OnCameraFrame;
lock (_frameLock)
{
_destroyed = true;
_pending?.Dispose();
_pending = null;
}
// 相机与推理管线是应用级单例,由 App.OnExit 按顺序统一释放。
base.Destroy();
}
/// <summary>
/// 扫描 configs/sop/*.yaml
/// </summary>
private void LoadRecipes()
{
if (!Directory.Exists(RecipeDirectory)) return;
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
}
/// <summary>
/// 编辑器保存后:重扫目录(新建的文件要能选到),选中刚存的那个,再重新应用一次
/// </summary>
private void RefreshRecipes(string fileName)
{
Recipes.Clear();
if (Directory.Exists(RecipeDirectory))
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
var pick = Recipes.Contains(fileName) ? fileName : Recipes.FirstOrDefault();
if (pick is not null) SelectedRecipe = pick;
ApplyRecipe();
}
/// <summary>
/// 编辑当前选中的配方
/// </summary>
private void EditRecipe()
{
var path = Path.Combine(RecipeDirectory, SelectedRecipe!);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
return;
}
// 编辑器读的是这个已解析的 config(含校验提醒),保存时再整体映射回去
OpenEditor(path, false, SopConfigLoader.Load(path));
}
/// <summary>
/// 新建配方(空白配方,文件名在编辑器里填)
/// </summary>
private void NewRecipe()
{
OpenEditor("", true, new SopConfig());
}
/// <summary>
/// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
/// </summary>
private void OpenEditor(string path, bool isNew, SopConfig config)
{
var parameters = new DialogParameters();
parameters.Add("directory", RecipeDirectory);
parameters.Add("path", path);
parameters.Add("new", isNew);
parameters.Add("config", config);
parameters.Add("onSaved", new Action<string>(fileName =>
_dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
parameters.Add("cameraService", _camera);
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
if (Frame is BitmapSource image)
{
var preview = image.Clone();
preview.Freeze();
parameters.Add("preview", preview);
}
_dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
}
private void LoadLastCamera()
{
try
{
if (File.Exists(LastCameraPath))
_lastUsedCamera = JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(LastCameraPath));
}
catch (Exception ex)
{
Log("warn", $"读取上次使用的相机失败:{ex.Message}");
}
}
private void RememberCamera(CameraInfo camera)
{
_lastUsedCamera = camera;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(LastCameraPath)!);
File.WriteAllText(LastCameraPath, JsonSerializer.Serialize(camera));
}
catch (Exception ex)
{
Log("warn", $"保存上次使用的相机失败:{ex.Message}");
}
}
private async Task RefreshCamerasAsync()
{
if (_destroyed || !CanSelectCamera) return;
SetCameraBusy(true);
try
{
var previous = SelectedCamera ?? _lastUsedCamera;
SelectedCamera = null;
Cameras.Clear();
var cameras = await _camera.EnumerateAsync();
if (_destroyed) return;
foreach (var info in cameras)
Cameras.Add(info);
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到相机(支持 UVC、海康 GigE/USB 工业相机)");
return;
}
SelectedCamera = Cameras.FirstOrDefault(c => c.Kind == previous?.Kind &&
(c.Kind == CameraKind.Hikvision ? c.SerialNumber == previous.SerialNumber : c.Index == previous.Index))
?? Cameras[0];
Log("info", $"枚举到 {Cameras.Count} 个相机");
}
catch (Exception ex)
{
Log("warn", $"刷新相机失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
private async Task StartStopAsync()
{
if (_isCameraBusy) return;
SetCameraBusy(true);
try { await StartStopCoreAsync(); }
catch (Exception ex)
{
await Task.Run(_camera.Disconnect);
IsRunning = false;
StatusText = "启动失败";
Log("warn", $"相机操作失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
private async Task StartStopCoreAsync()
{
if (IsRunning)
{
await Task.Run(() =>
{
_pipeline.Stop();
// Recording opens its own capture session; stopping SOP must release the device.
_camera.Disconnect();
});
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();
if (_engine.Config.Sop.Settings.ExposureTimeUs is { } exposure)
{
try
{
if (!double.IsFinite(exposure) || exposure <= 0)
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
await _camera.SetExposureTimeAsync(exposure);
}
catch (Exception ex)
{
Log("error", "设置相机曝光失败:" + ex.Message);
await Task.Run(_camera.Disconnect);
StatusText = "设置相机曝光失败";
return;
}
}
// 阈值 / 抽帧从界面参数覆盖配方默认值
_pipeline.SetThresholds((float)Confidence, 0.45f);
_engine.Config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
if (!await _pipeline.StartAsync())
{
await Task.Run(_camera.Disconnect);
Log("warn", "采集启动失败");
return;
}
_engine.Start();
IsRunning = true;
RememberCamera(SelectedCamera);
StatusText = "运行中";
}
private void ApplyRecipe()
{
HandResult = null;
if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
var path = Path.Combine(RecipeDirectory, 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,
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
PalmModelPath = ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx"),
LandmarkModelPath = ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx"),
FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
};
_pipeline.LoadModels(options);
Log("info", $"推理设备:手部={_pipeline.HandBackend},YOLO={_pipeline.YoloBackend}");
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);
if (options.PalmModelPath is null || options.LandmarkModelPath is null)
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
}
/// <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)
{
if (_destroyed || !IsRunning) return;
lock (_frameLock)
{
_lastFrame = result;
}
_engine.ProcessFrame(result);
// 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。
HandResult = 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;
if (HandResult?.Size != (src.Cols, src.Rows)) HandResult = null;
}
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));
}

View File

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -15,12 +15,12 @@
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" AdditionalProperties="NativePlatform=$(NativePlatform)" />
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
<PackageReference Include="Prism.DryIoc.Avalonia" Version="9.0.537.11130" />
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.22" />
<AvaloniaResource Include="Assets/**" />
<Content Include="../SopHelper.App/Assets/bws.svg" Link="Assets/bws.svg" CopyToOutputDirectory="PreserveNewest" />
<Content Include="Assets/bws.svg" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../configs/**/*" Link="configs/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../models/*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../yolo_models/*.onnx" Link="yolo_models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />

View File

@ -110,8 +110,8 @@ public sealed class MainViewModel : BindableBase
{
_worker = worker;
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx"))) directory = directory.Parent;
Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx")) ? directory.FullName : AppContext.BaseDirectory;
while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.Avalonia.slnx"))) directory = directory.Parent;
Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.Avalonia.slnx")) ? directory.FullName : AppContext.BaseDirectory;
LoadSettings();
ImportCommand = Command(Import);
OpenCommand = Command(async () =>

View File

@ -4,7 +4,6 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<NativePlatform Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('linux'))">Linux</NativePlatform>
<NativePlatform Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('win'))">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
@ -13,8 +12,6 @@
<MvsManagedSdk Condition="'$(MvsManagedSdk)' == ''">../../libs/MvCameraControl.Net.dll</MvsManagedSdk>
</PropertyGroup>
<ItemGroup>
<Compile Include="../SopHelper.Engine/**/*.cs" Exclude="../SopHelper.Engine/obj/**;../SopHelper.Engine/bin/**;../SopHelper.Engine/Camera/UvcCameraService.cs" Link="Engine/%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="*.cs" />
<Reference Include="MvCameraControl.Net"><HintPath>$(MvsManagedSdk)</HintPath><Private>true</Private></Reference>
<PackageReference Include="OpenCvSharp4" Version="4.13.0.20260627" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.13.0.20260627" Condition="'$(NativePlatform)' == 'Windows'" />

View File

@ -1,288 +0,0 @@
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
/// <summary>
/// USB(UVC)相机实现。单相机最小版。
/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
/// </summary>
public class UvcCameraService : ICameraService
{
/// <summary>
/// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
/// 旧图还在异步销毁时开新图会触发 AccessViolationException。
/// </summary>
private static readonly object DshowLock = new();
private readonly object _captureLock = new();
private VideoCapture? _capture;
private CancellationTokenSource? _cts;
private Task? _grabTask;
private long _frameId;
/// <inheritdoc />
public bool IsConnected { get; private set; }
/// <inheritdoc />
public bool IsGrabbing { get; private set; }
/// <inheritdoc />
public event Action<CameraFrame>? FrameArrived;
/// <inheritdoc />
public event Action<bool>? ConnectionChanged;
/// <inheritdoc />
public event Action<string>? Error;
/// <summary>当前相机</summary>
public CameraInfo? Current { get; private set; }
/// <summary>实测帧率(每 2 秒刷新一次)</summary>
public double ActualFps { get; private set; }
/// <inheritdoc />
public Task<List<CameraInfo>> EnumerateAsync()
{
return Task.Run(() =>
{
var list = new List<CameraInfo>();
for (var i = 0; i <= 10; i++)
{
var index = i;
// 跳过本进程已占用的索引:对同一设备重复开 DSHOW 图会原生崩溃
lock (_captureLock)
{
if (_capture is not null && Current?.Index == index)
{
list.Add(new CameraInfo { Index = index, Name = $"Camera {index}(当前已连接)" });
continue;
}
}
lock (DshowLock)
{
try
{
using var probe = new VideoCapture(index, VideoCaptureAPIs.DSHOW);
if (!probe.IsOpened()) continue;
var w = probe.Get(VideoCaptureProperties.FrameWidth);
var h = probe.Get(VideoCaptureProperties.FrameHeight);
if (w <= 0 || h <= 0) continue;
list.Add(new CameraInfo { Index = index, Name = $"Camera {index}({w:F0}x{h:F0})" });
}
catch
{
// 探测失败的设备跳过即可
}
}
}
return list;
});
}
/// <inheritdoc />
public Task<bool> ConnectAsync(CameraInfo camera)
{
return Task.Run(() =>
{
lock (DshowLock)
{
lock (_captureLock)
{
if (_capture is not null)
{
_capture.Dispose();
_capture = null;
}
// MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
// 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
_capture = TryOpen(camera.Index, VideoCaptureAPIs.MSMF)
?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW);
if (_capture is null)
{
Error?.Invoke($"相机 {camera.Index} 打不开(MSMF 与 DSHOW 均失败)");
return false;
}
}
}
Current = camera;
IsConnected = true;
ConnectionChanged?.Invoke(true);
return true;
});
}
/// <inheritdoc />
public Task<bool> StartAsync()
{
return Task.Run(() =>
{
VideoCapture capture;
lock (_captureLock)
{
if (_capture is null) return false;
capture = _capture;
}
if (IsGrabbing) return true;
_cts = new CancellationTokenSource();
IsGrabbing = true;
_grabTask = Task.Run(() => GrabLoop(capture, _cts.Token));
return true;
});
}
/// <summary>
/// 采集循环
/// </summary>
private void GrabLoop(VideoCapture capture, CancellationToken token)
{
var fpsWatch = System.Diagnostics.Stopwatch.StartNew();
var framesInWindow = 0;
while (!token.IsCancellationRequested)
{
var frame = new Mat();
bool ok;
lock (_captureLock)
{
if (captureDisposed) break;
ok = capture.Read(frame);
}
if (!ok || frame.Empty())
{
frame.Dispose();
// 读不到帧时轻微退避,不空转
Thread.Sleep(20);
continue;
}
// ⚠ 成功取帧后不强制 Sleep:Read 本身按相机帧节拍阻塞,
// 补一个 Sleep(33) 会把采集帧率白扣一半(参考项目实测踩过)。
_frameId++;
framesInWindow++;
if (fpsWatch.ElapsedMilliseconds >= 2000)
{
ActualFps = framesInWindow * 1000.0 / fpsWatch.ElapsedMilliseconds;
fpsWatch.Restart();
framesInWindow = 0;
}
var cameraFrame = new CameraFrame
{
FrameId = _frameId,
Timestamp = DateTime.Now,
Bgr = frame,
};
try
{
FrameArrived?.Invoke(cameraFrame);
}
catch (Exception ex)
{
Error?.Invoke($"帧回调异常: {ex.Message}");
}
finally
{
cameraFrame.Dispose();
}
}
IsGrabbing = false;
}
private volatile bool captureDisposed;
/// <inheritdoc />
public void Stop()
{
_cts?.Cancel();
try
{
_grabTask?.Wait(TimeSpan.FromSeconds(2));
}
catch
{
// 取消异常忽略
}
_grabTask = null;
_cts?.Dispose();
_cts = null;
IsGrabbing = false;
}
/// <inheritdoc />
public void Disconnect()
{
Stop();
lock (DshowLock)
{
lock (_captureLock)
{
if (_capture is not null)
{
captureDisposed = true;
_capture.Dispose();
_capture = null;
captureDisposed = false;
}
}
// 给系统一点时间把原生图销毁干净,紧接的 ConnectAsync 才安全
Thread.Sleep(500);
}
IsConnected = false;
Current = null;
ConnectionChanged?.Invoke(false);
}
/// <inheritdoc />
public void Dispose()
{
Disconnect();
}
/// <summary>
/// 用指定后端尝试打开
/// </summary>
private static VideoCapture? TryOpen(int index, VideoCaptureAPIs api)
{
try
{
var capture = new VideoCapture(index, api);
if (!capture.IsOpened())
{
capture.Dispose();
return null;
}
return capture;
}
catch
{
return null;
}
}
}

View File

@ -1,31 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- 纯类库:相机采集 + 推理 + SOP 判定引擎,不含任何 UI 依赖(可单测、可复用) -->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<PlatformTarget>x64</PlatformTarget>
<Platforms>AnyCPU;x64</Platforms>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>SopHelper.Engine</RootNamespace>
<AssemblyName>SopHelper.Engine</AssemblyName>
</PropertyGroup>
<ItemGroup>
<Reference Include="MvCameraControl.Net">
<HintPath>..\..\libs\MvCameraControl.Net.dll</HintPath>
<Private>true</Private>
</Reference>
<PackageReference Include="OpenCvSharp4.Windows" Version="4.10.0.20241108" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Gpu" Version="1.23.0" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\libs\cuda\*.dll" Link="%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="..\..\libs\cuda\LICENSE*" Link="licenses\cudnn\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="../SopHelper.Engine/Common/*.cs" Link="Common/%(Filename)%(Extension)" />
<Compile Include="../SopHelper.Engine/Sop/*.cs" Link="Sop/%(Filename)%(Extension)" />
<Compile Include="../SopHelper.Engine/Inference/*.cs" Link="Inference/%(Filename)%(Extension)" />
<Compile Include="../SopHelper.Engine/Training/*.cs" Link="Training/%(Filename)%(Extension)" />
<Compile Include="../SopHelper.Engine/Camera/ICameraService.cs" Link="Camera/ICameraService.cs" />
<Compile Include="../SopHelper.Engine/Camera/VideoRecorder.cs" Link="Camera/VideoRecorder.cs" />
<PackageReference Include="OpenCvSharp4" Version="4.13.0.20260627" />
<PackageReference Include="OpenCvSharp4.official.runtime.linux-x64" Version="4.13.0.20260627" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.0" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
</ItemGroup>
</Project>

View File

@ -1,164 +0,0 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
using SopHelper.Engine.Sop;
namespace SopHelper.Linux;
internal sealed record PreviewFrame(byte[] Jpeg, double InferenceMs, double ResultFps, int Objects, int Hands, int Width, int Height);
internal sealed class DetectionSession : IDisposable
{
private readonly ConcurrentQueue<string> _commands = new();
private readonly object _frameGate = new();
private Mat? _lastFrame;
public event Action<PreviewFrame>? Preview;
public event Action<StepSnapshot>? Step;
public event Action<string>? Log;
public event Action<string>? Status;
private void WriteLog(string message)
{
var line = $"{DateTime.Now:HH:mm:ss} {message}";
Directory.CreateDirectory("workspace/logs");
File.AppendAllText($"workspace/logs/{DateTime.Now:yyyy-MM-dd}.log", line + Environment.NewLine);
Log?.Invoke(line);
}
public void Command(string command) => _commands.Enqueue(command);
public string Snapshot()
{
lock (_frameGate)
{
if (_lastFrame is null) throw new InvalidOperationException("还没有画面,请先开始采集");
Directory.CreateDirectory("workspace/snaps");
var path = $"workspace/snaps/{DateTime.Now:yyyyMMdd-HHmmss-fff}.png";
if (!Cv2.ImWrite(path, _lastFrame)) throw new IOException("快照写入失败");
return Path.GetFullPath(path);
}
}
public Task RunAsync(string source, SopConfig config, bool useYolo, bool useHands, CancellationToken token) => Task.Run(async () =>
{
try
{
while (_commands.TryDequeue(out _)) { }
Status?.Invoke("正在加载模型…");
using var yolo = new YoloDetector();
using var hands = new MediaPipeHandDetector();
using var recorder = new VideoRecorder();
if (useYolo)
{
var model = config.Sop.Model;
yolo.Load(model?.Path is { Length: > 0 } path ? path : "models/yolo11n.onnx", model?.Classes ?? [], model?.InputSize ?? 640, false);
if (!yolo.IsReady) throw new FileNotFoundException("YOLO 模型未加载");
yolo.SetThresholds(config.Sop.Settings.ConfidenceThreshold, .45f);
}
if (useHands)
{
hands.Load("models/palm_detection_full_Nx3x192x192_post.onnx", "models/hand_landmark_sparse_Nx3x224x224.onnx", false);
if (!hands.IsReady) throw new FileNotFoundException("手部模型未加载");
}
token.ThrowIfCancellationRequested();
using var capture = int.TryParse(source, out var index)
? new VideoCapture(index, VideoCaptureAPIs.V4L2)
: source.StartsWith("/dev/video") ? new VideoCapture(source, VideoCaptureAPIs.V4L2) : new VideoCapture(source);
if (!capture.IsOpened()) throw new IOException($"无法打开输入:{source}。UVC 请检查连接和设备权限;海康相机需要 Linux MVS 后端。");
var isFile = File.Exists(source) && !source.StartsWith("/dev/");
if (!isFile) capture.Set(VideoCaptureProperties.BufferSize, 1);
var fileFps = capture.Fps;
if (!double.IsFinite(fileFps) || fileFps < 1 || fileFps > 240) fileFps = 25;
var engine = new SopEngine();
// Keep delayed reset on this worker so stop/dispose cannot leave a pending reset task.
var autoReset = config.Sop.Settings.AutoResetOnComplete;
config.Sop.Settings.AutoResetOnComplete = false;
engine.StepSnapshotChanged += s => Step?.Invoke(s);
engine.LogArrived += l => WriteLog(l.Message);
engine.Load(config); engine.Start();
using var raw = new Mat();
long frameId = 0, processed = 0;
var wall = Stopwatch.StartNew();
var completeAt = TimeSpan.MaxValue;
WriteLog($"输入:{source};CPU {Environment.GetEnvironmentVariable("SOPHELPER_CPU_THREADS")} 线程;YOLO={useYolo};双手={useHands}");
Status?.Invoke("运行中 · CPU");
while (!token.IsCancellationRequested)
{
var frameClock = Stopwatch.StartNew();
if (!capture.Read(raw) || raw.Empty())
{
if (!isFile) throw new IOException("相机未返回有效画面,采集已停止");
WriteLog("视频播放结束"); break;
}
frameId++;
while (_commands.TryDequeue(out var command))
{
if (command == "reset") { engine.Reset(); completeAt = TimeSpan.MaxValue; }
if (command == "pause") { engine.TogglePause(); Status?.Invoke(engine.State == EngineState.Paused ? "已暂停 SOP · 采集继续" : "运行中 · CPU"); }
if (command == "record")
{
if (recorder.IsRecording) WriteLog($"录像已保存:{recorder.Stop()?.Path}");
else WriteLog($"开始录像:{recorder.Start("workspace/recordings", raw, fileFps)}");
}
}
recorder.Write(raw);
if (frameId % Math.Max(1, config.Sop.Settings.FrameStride) != 0)
{
if (isFile) await Task.Delay(TimeSpan.FromMilliseconds(1000.0 / fileFps), token);
continue;
}
var inference = Stopwatch.StartNew();
var result = new FrameResult { FrameId = frameId, Timestamp = DateTime.Now, Size = (raw.Width, raw.Height) };
if (useYolo) result.Detections = yolo.Detect(raw);
if (useHands) result.Hands = hands.Detect(raw);
inference.Stop(); result.InferenceMs = inference.Elapsed.TotalMilliseconds;
engine.ProcessFrame(result);
if (engine.State == EngineState.Completed && completeAt == TimeSpan.MaxValue) completeAt = wall.Elapsed;
if (autoReset && wall.Elapsed - completeAt >= TimeSpan.FromSeconds(Math.Max(1, config.Sop.Settings.ResetDelaySec)))
{ engine.Reset(); completeAt = TimeSpan.MaxValue; }
lock (_frameGate) { _lastFrame?.Dispose(); _lastFrame = raw.Clone(); }
using var display = raw.Clone();
Draw(display, result, config);
// Preview encoding and display are included in the observed processing rate.
Cv2.ImEncode(".jpg", display, out var jpeg, new ImageEncodingParam(ImwriteFlags.JpegQuality, 85));
processed++;
Preview?.Invoke(new PreviewFrame(jpeg, result.InferenceMs, processed / wall.Elapsed.TotalSeconds,
result.Detections.Count, result.Hands.Count, raw.Width, raw.Height));
if (isFile)
{
var delay = 1000.0 / fileFps - frameClock.Elapsed.TotalMilliseconds;
if (delay > 0) await Task.Delay(TimeSpan.FromMilliseconds(delay), token);
}
}
if (recorder.IsRecording) WriteLog($"录像已保存:{recorder.Stop()?.Path}");
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception ex) { WriteLog($"错误:{ex.Message}"); Status?.Invoke("运行失败 · 详见日志"); throw; }
finally { Status?.Invoke("已停止"); }
}, token);
private static readonly (int, int)[] Bones = [(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(5,9),(9,10),(10,11),(11,12),(9,13),(13,14),(14,15),(15,16),(13,17),(0,17),(17,18),(18,19),(19,20)];
internal static void Draw(Mat frame, FrameResult result, SopConfig config)
{
foreach (var (name, region) in config.Sop.Regions)
{
Cv2.Rectangle(frame, new Point(region.X1, region.Y1), new Point(region.X2, region.Y2), new Scalar(180, 130, 70), 2);
Cv2.PutText(frame, name, new Point(region.X1, Math.Max(20, region.Y1 - 8)), HersheyFonts.HersheySimplex, .6, Scalar.White, 1);
}
foreach (var d in result.Detections)
{
var r = d.Rect;
Cv2.Rectangle(frame, new Point(r.X,r.Y), new Point(r.Right,r.Bottom), new Scalar(70,210,160), 2);
Cv2.PutText(frame, $"{d.Label} {d.Confidence:F2}", new Point(r.X,Math.Max(20,r.Y-6)), HersheyFonts.HersheySimplex,.6,Scalar.White,1);
}
foreach (var hand in result.Hands)
{
var color = hand.HandType == HandType.Left ? new Scalar(80,230,80) : new Scalar(240,170,40);
var points = hand.Keypoints.Where(p => float.IsFinite(p.X) && float.IsFinite(p.Y)).ToDictionary(p=>p.Index);
foreach (var (a,b) in Bones)
if (points.TryGetValue(a,out var x) && points.TryGetValue(b,out var y))
Cv2.Line(frame,new Point(x.X,x.Y),new Point(y.X,y.Y),color,2);
foreach (var p in points.Values) Cv2.Circle(frame,new Point(p.X,p.Y),3,Scalar.Yellow,-1);
}
}
public void Dispose() { lock (_frameGate) { _lastFrame?.Dispose(); _lastFrame = null; } }
}

View File

@ -1,239 +0,0 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using SopHelper.Engine.Sop;
using System.Text.Json;
namespace SopHelper.Linux;
internal sealed class MainWindow : Window
{
private readonly TextBox _source = new() { Text = "0", Watermark = "UVC 编号、/dev/video0 或视频路径", Width = 300 };
private readonly ComboBox _recipes = new() { MinWidth = 200 };
private readonly CheckBox _yolo = new() { Content = "YOLO 目标", IsChecked = true };
private readonly CheckBox _hands = new() { Content = "双手关键点", IsChecked = true };
private readonly Image _preview = new() { Stretch = Stretch.Uniform };
private readonly TextBlock _empty = new() { Text = "连接 UVC 相机或打开视频\n点击「开始检测」", FontSize = 22, Foreground = Brushes.Gray,
HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center };
private readonly TextBlock _status = new() { Text = "就绪 · CPU 推理", Foreground = Brush.Parse("#68DDB4"), FontSize = 14 };
private readonly TextBlock _metrics = new() { Text = "处理帧率 — 推理耗时 — 目标 — 手 —", Foreground = Brushes.LightGray };
private readonly TextBox _logs = new() { IsReadOnly = true, AcceptsReturn = true, TextWrapping = TextWrapping.Wrap, MinHeight = 110 };
private readonly StackPanel _steps = new() { Spacing = 8 };
private readonly TextBox _yaml = new() { AcceptsReturn = true, AcceptsTab = true, FontFamily = new FontFamily("monospace"), FontSize = 14,
HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch };
private readonly Dictionary<int, TextBlock> _stepLabels = [];
private readonly DetectionSession _session = new();
private readonly Button _start;
private readonly Button _stop;
private CancellationTokenSource? _cts;
private Task? _running;
private Bitmap? _bitmap;
private PreviewFrame? _pendingFrame;
private readonly DispatcherTimer _displayTimer;
private bool _closing, _allowClose;
private string RecipePath => (_recipes.SelectedItem as RecipeChoice)?.Path ?? throw new InvalidOperationException("请先选择配方");
public MainWindow()
{
Title = "SopHelper · Linux 工位检测";
Width = 1380; Height = 900; MinWidth = 1060; MinHeight = 700;
Background = Brush.Parse("#111720");
FontFamily = new FontFamily("Noto Sans CJK SC, WenQuanYi Micro Hei, sans-serif");
_start = Button("开始检测", async () => await StartAsync());
_stop = Button("停止", async () => await StopAsync()); _stop.IsEnabled = false;
var toolbar = new WrapPanel { Orientation = Orientation.Horizontal, ItemSpacing = 10, LineSpacing = 8 };
toolbar.Children.Add(_source);
toolbar.Children.Add(Button("打开视频", OpenVideoAsync));
toolbar.Children.Add(Button("扫描 UVC", ScanCamerasAsync));
toolbar.Children.Add(_recipes);
toolbar.Children.Add(_yolo); toolbar.Children.Add(_hands);
toolbar.Children.Add(_start); toolbar.Children.Add(_stop);
var commands = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Margin = new Thickness(0,10,0,0) };
commands.Children.Add(Button("暂停 / 继续 SOP", () => SendCommandAsync("pause")));
commands.Children.Add(Button("复位", () => SendCommandAsync("reset")));
commands.Children.Add(Button("保存快照", () => { AddLog("快照:" + _session.Snapshot()); return Task.CompletedTask; }));
commands.Children.Add(Button("开始 / 停止录像", () => SendCommandAsync("record")));
commands.Children.Add(_status);
var previewGrid = new Grid(); previewGrid.Children.Add(_preview); previewGrid.Children.Add(_empty);
var videoCard = new Border { Background = Brush.Parse("#080D13"), CornerRadius = new CornerRadius(10), Child = previewGrid };
var body = new Grid { ColumnDefinitions = new ColumnDefinitions("*,320"), Margin = new Thickness(0,14,0,10) };
body.Children.Add(videoCard);
var side = new StackPanel { Spacing = 12, Margin = new Thickness(16,0,0,0) };
side.Children.Add(new TextBlock { Text = "作业步骤", FontSize = 22, FontWeight = FontWeight.SemiBold });
side.Children.Add(new TextBlock { Text = "配方坐标为相机原图像素。\n示例配方需按现场重新标定。", Foreground = Brushes.Gray, TextWrapping = TextWrapping.Wrap });
side.Children.Add(new ScrollViewer { Content = _steps });
Grid.SetColumn(side,1); body.Children.Add(side);
var detection = new Grid { RowDefinitions = new RowDefinitions("Auto,Auto,*,Auto,150"), Margin = new Thickness(16) };
detection.Children.Add(toolbar); Grid.SetRow(commands,1); detection.Children.Add(commands);
Grid.SetRow(body,2); detection.Children.Add(body);
Grid.SetRow(_metrics,3); detection.Children.Add(_metrics);
Grid.SetRow(_logs,4); detection.Children.Add(_logs);
var editorToolbar = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, Margin = new Thickness(0,0,0,10) };
editorToolbar.Children.Add(Button("重新载入", () => { LoadRecipe(); return Task.CompletedTask; }));
editorToolbar.Children.Add(Button("校验并保存", SaveRecipeAsync));
editorToolbar.Children.Add(new TextBlock { Text = "停止检测后编辑;保存前校验并自动备份", VerticalAlignment = VerticalAlignment.Center });
var editor = new DockPanel { Margin = new Thickness(16) };
DockPanel.SetDock(editorToolbar,Dock.Top); editor.Children.Add(editorToolbar); editor.Children.Add(_yaml);
var tabs = new TabControl { ItemsSource = new[] {
new TabItem { Header = "工位检测", Content = detection },
new TabItem { Header = "配方 YAML", Content = editor }
}};
var layout = new DockPanel();
var heading = new StackPanel { Margin = new Thickness(22,16,22,12), Spacing = 4 };
heading.Children.Add(new TextBlock { Text = "SopHelper", FontSize = 28, FontWeight = FontWeight.Bold });
heading.Children.Add(new TextBlock { Text = "单相机 SOP 辅助 / Linux 桌面版", Foreground = Brushes.Gray });
DockPanel.SetDock(heading,Dock.Top); layout.Children.Add(heading); layout.Children.Add(tabs); Content = layout;
_session.Log += line => Dispatcher.UIThread.Post(() => AddLog(line));
_session.Status += text => Dispatcher.UIThread.Post(() => _status.Text = text);
_session.Step += step => Dispatcher.UIThread.Post(() => UpdateStep(step));
_session.Preview += frame => Interlocked.Exchange(ref _pendingFrame,frame);
_displayTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(66), DispatcherPriority.Background, (_,_) => ShowPendingFrame());
_recipes.SelectionChanged += (_,_) => { if (_recipes.SelectedItem is not null) Try(LoadRecipe); };
_recipes.ItemsSource = Directory.GetFiles("configs/sop","*.yaml").Order().Select(p => new RecipeChoice(p)).ToArray();
_recipes.SelectedIndex = 0;
Try(LoadSettings);
Closing += async (_,e) =>
{
if (_allowClose) return;
e.Cancel = true; if (_closing) return; _closing = true;
await StopAsync(); _displayTimer.Stop(); _session.Dispose(); _bitmap?.Dispose();
_allowClose = true; Close();
};
Opened += async (_,_) =>
{
AddLog("CPU 推理已配置。YOLO、手掌、21 点关键点复用 Windows 版实现。");
if (Program.UiSmoke)
{
_source.Text = Path.GetFullPath("workspace/smoke-input.avi");
await StartAsync();
for (var i = 0; i < 100 && _bitmap is null; i++) await Task.Delay(100);
if (_bitmap is null) throw new IOException("UI 测试未收到视频预览");
_session.Command("pause");
_session.Command("record");
await Task.Delay(600);
_session.Command("pause");
_session.Command("reset");
var snapshot = _session.Snapshot();
await Task.Delay(300);
ShowPendingFrame();
using var image = new RenderTargetBitmap(new PixelSize((int)Bounds.Width,(int)Bounds.Height));
image.Render(this); image.Save("workspace/ui-smoke.png");
File.WriteAllText("workspace/ui-smoke.json", JsonSerializer.Serialize(new { window = Title, preview = _bitmap is not null,
steps = _stepLabels.Count, status = _status.Text, metrics = _metrics.Text, snapshot = File.Exists(snapshot) }));
await StopAsync(); Close();
}
};
}
private static Button Button(string text, Func<Task> action)
{
var button = new Button { Content = text, VerticalAlignment = VerticalAlignment.Center, Padding = new Thickness(14,9) };
button.Click += async (_,_) => { try { await action(); } catch(Exception ex) { if (TopLevel.GetTopLevel(button) is MainWindow w) w.AddLog("错误:" + ex.Message); } };
return button;
}
private void Try(Action action) { try { action(); } catch(Exception ex) { AddLog("错误:" + ex.Message); } }
private Task SendCommandAsync(string command)
{
if (_running is not { IsCompleted: false }) throw new InvalidOperationException("请先开始采集");
_session.Command(command); return Task.CompletedTask;
}
private void AddLog(string text)
{
var content = (_logs.Text ?? "") + text + Environment.NewLine;
_logs.Text = content.Length > 30000 ? content[^20000..] : content;
_logs.CaretIndex = _logs.Text.Length;
}
private void LoadRecipe()
{
if (_running is { IsCompleted: false }) throw new InvalidOperationException("请先停止检测");
var config = SopConfigLoader.Load(RecipePath);
_yaml.Text = File.ReadAllText(RecipePath);
_steps.Children.Clear(); _stepLabels.Clear();
foreach(var step in config.Sop.Steps.OrderBy(s=>s.Id))
{
var label = new TextBlock { Text = $"{step.Id:00} {step.Name}\n等待判定", TextWrapping = TextWrapping.Wrap, FontSize = 16 };
_stepLabels[step.Id] = label;
_steps.Children.Add(new Border { Padding = new Thickness(12), CornerRadius = new CornerRadius(6), Background = Brush.Parse("#202B38"), Child = label });
}
foreach(var warning in config.Warnings) AddLog("配方提示:" + warning);
}
private Task SaveRecipeAsync()
{
if (_running is { IsCompleted: false }) throw new InvalidOperationException("请先停止检测");
var config = SopConfigLoader.Parse(_yaml.Text ?? "");
if (config.Sop.Steps.Count == 0 || config.Warnings.Count > 0)
throw new InvalidDataException("配方未保存:" + string.Join(";",config.Warnings.DefaultIfEmpty("步骤为空")));
File.Copy(RecipePath,RecipePath + $".{DateTime.Now:yyyyMMddHHmmssfff}.bak");
var temporary = RecipePath + ".new";
File.WriteAllText(temporary,_yaml.Text); File.Move(temporary,RecipePath,true);
LoadRecipe(); AddLog("配方已校验、备份并保存"); return Task.CompletedTask;
}
private void UpdateStep(StepSnapshot step)
{
if (!_stepLabels.TryGetValue(step.StepId,out var label)) return;
label.Text = $"{step.StepId:00} {step.Name}\n{step.Message}";
label.Foreground = step.IsMet ? Brush.Parse("#68DDB4") : step.IsCurrent ? Brushes.White : Brushes.Gray;
}
private async Task OpenVideoAsync()
{
if (_running is { IsCompleted: false }) throw new InvalidOperationException("请先停止检测");
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "选择测试视频", AllowMultiple = false,
FileTypeFilter = new[] { new FilePickerFileType("视频") { Patterns = new[] { "*.mp4","*.avi","*.mkv","*.mov" } } } });
if (files.Count > 0) _source.Text = files[0].TryGetLocalPath();
}
private Task ScanCamerasAsync()
{
var cameras = Directory.GetFiles("/dev","video*").Order().ToArray();
AddLog(cameras.Length == 0 ? "未发现 UVC 相机。请连接 USB 相机,或使用视频文件验证。海康工业相机需安装 Linux MVS。" : "视频设备:" + string.Join(",",cameras));
if (cameras.Length > 0) _source.Text = cameras[0];
return Task.CompletedTask;
}
private Task StartAsync()
{
if (_running is { IsCompleted: false }) return Task.CompletedTask;
var source = _source.Text?.Trim(); if (string.IsNullOrEmpty(source)) throw new InvalidOperationException("请输入相机编号或视频路径");
LoadRecipe();
var config = SopConfigLoader.Load(RecipePath);
_cts?.Dispose(); _cts = new CancellationTokenSource();
_start.IsEnabled = false; _stop.IsEnabled = true; _recipes.IsEnabled = false; _yaml.IsReadOnly = true;
if (!Program.UiSmoke) SaveSettings();
_running = _session.RunAsync(source,config,_yolo.IsChecked == true,_hands.IsChecked == true,_cts.Token);
_ = ObserveAsync(_running);
return Task.CompletedTask;
}
private async Task ObserveAsync(Task task)
{
try { await task; } catch (OperationCanceledException) { } catch (Exception ex) { AddLog("检测已停止:" + ex.Message); }
finally { _start.IsEnabled = true; _stop.IsEnabled = false; _recipes.IsEnabled = true; _yaml.IsReadOnly = false; }
}
private async Task StopAsync()
{
_cts?.Cancel();
if (_running is not null) { try { await _running; } catch { /* ObserveAsync reports failures. */ } }
}
private void ShowPendingFrame()
{
var frame = Interlocked.Exchange(ref _pendingFrame,null); if (frame is null) return;
using var stream = new MemoryStream(frame.Jpeg);
var bitmap = new Bitmap(stream); _preview.Source = bitmap; _bitmap?.Dispose(); _bitmap = bitmap; _empty.IsVisible = false;
_metrics.Text = $"处理帧率 {frame.ResultFps:F1} FPS 推理 {frame.InferenceMs:F1} ms 目标 {frame.Objects} 手 {frame.Hands} 原图 {frame.Width} × {frame.Height}";
}
private sealed record RecipeChoice(string Path) { public override string ToString() => System.IO.Path.GetFileNameWithoutExtension(Path); }
private void SaveSettings()
{
Directory.CreateDirectory("workspace");
File.WriteAllText("workspace/linux-settings.json",JsonSerializer.Serialize(new Settings(_source.Text ?? "0",RecipePath,_yolo.IsChecked == true,_hands.IsChecked == true)));
}
private void LoadSettings()
{
if (!File.Exists("workspace/linux-settings.json")) return;
var settings = JsonSerializer.Deserialize<Settings>(File.ReadAllText("workspace/linux-settings.json")); if (settings is null) return;
_source.Text = settings.Source; _yolo.IsChecked = settings.Yolo; _hands.IsChecked = settings.Hands;
if (_recipes.ItemsSource is RecipeChoice[] choices && choices.FirstOrDefault(c=>c.Path==settings.Recipe) is {} selected) _recipes.SelectedItem=selected;
}
private sealed record Settings(string Source,string Recipe,bool Yolo,bool Hands);
}

View File

@ -1,127 +0,0 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Themes.Fluent;
using Avalonia.Styling;
using OpenCvSharp;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
using SopHelper.Engine.Sop;
using System.Diagnostics;
using System.Text.Json;
namespace SopHelper.Linux;
internal static class Program
{
public static string Root => AppContext.BaseDirectory;
public static bool UiSmoke;
[STAThread]
public static int Main(string[] args)
{
Directory.SetCurrentDirectory(Root);
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS",
Environment.GetEnvironmentVariable("SOPHELPER_CPU_THREADS") ?? Math.Min(8, Environment.ProcessorCount).ToString());
if (args.Contains("--self-test")) return SelfTest.Run();
if (Array.IndexOf(args, "--video-test") is var videoIndex && videoIndex >= 0)
return videoIndex + 1 < args.Length ? SelfTest.Video(args[videoIndex + 1]) : 2;
UiSmoke = args.Contains("--ui-smoke");
return AppBuilder.Configure<DesktopApp>().UsePlatformDetect()
.LogToTrace().StartWithClassicDesktopLifetime(args);
}
}
internal sealed class DesktopApp : Application
{
public override void Initialize()
{
RequestedThemeVariant = ThemeVariant.Dark;
Styles.Add(new FluentTheme());
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow();
base.OnFrameworkInitializationCompleted();
}
}
internal static class SelfTest
{
public static int Video(string path)
{
try
{
using var yolo = new YoloDetector(); using var hand = new MediaPipeHandDetector();
yolo.Load("models/yolo11n.onnx", [], 640, false);
hand.Load("models/palm_detection_full_Nx3x192x192_post.onnx", "models/hand_landmark_sparse_Nx3x224x224.onnx", false);
using var capture = new VideoCapture(path); using var frame = new Mat();
if (!capture.IsOpened()) throw new IOException("测试视频无法打开");
var timings = new List<double>(); var maxHands = 0; var maxObjects = 0; var left = false; var right = false;
Directory.CreateDirectory("workspace");
for (var index = 0; index < 300 && capture.Read(frame); index++)
{
if (index % 5 != 0) continue;
var timer = Stopwatch.StartNew();
var result = new FrameResult { Detections = yolo.Detect(frame), Hands = hand.Detect(frame), Size = (frame.Width,frame.Height) };
timer.Stop(); timings.Add(timer.Elapsed.TotalMilliseconds);
maxObjects = Math.Max(maxObjects,result.Detections.Count);
left |= result.Hands.Any(h=>h.HandType==HandType.Left); right |= result.Hands.Any(h=>h.HandType==HandType.Right);
if (result.Hands.Any(h=>h.Keypoints.Count!=21)) throw new Exception("关键点输出不完整");
if (result.Hands.Count > maxHands)
{
maxHands = result.Hands.Count;
using var display = frame.Clone(); DetectionSession.Draw(display,result,new SopConfig());
Cv2.ImWrite("workspace/video-test-hands.jpg",display);
}
}
if (timings.Count == 0 || maxHands == 0) throw new Exception("测试视频没有产生手部结果");
var sorted=timings.Order().ToArray();
var json=JsonSerializer.Serialize(new { passed=true,frames=timings.Count,maxHands,left,right,maxObjects,
meanDetectionMs=timings.Average(), p95DetectionMs=sorted[(int)Math.Floor((sorted.Length-1)*.95)],
note="YOLO + actual hand pipeline including preprocessing and decoding; sampled video, no display or playback pacing" },new JsonSerializerOptions{WriteIndented=true});
File.WriteAllText("workspace/video-test.json",json); Console.WriteLine(json); return 0;
}
catch(Exception ex) { Console.Error.WriteLine(ex); return 1; }
}
public static int Run()
{
try
{
Directory.CreateDirectory("workspace");
using var yolo = new YoloDetector();
using var hand = new MediaPipeHandDetector();
yolo.Load("models/yolo11n.onnx", [], 640, false);
hand.Load("models/palm_detection_full_Nx3x192x192_post.onnx", "models/hand_landmark_sparse_Nx3x224x224.onnx", false);
if (!yolo.IsReady || !hand.IsReady) throw new Exception("模型未就绪");
using var frame = new Mat(480, 640, MatType.CV_8UC3, new Scalar(35, 28, 22));
Cv2.PutText(frame, "SopHelper Linux - SMOKE TEST", new OpenCvSharp.Point(35, 200), HersheyFonts.HersheySimplex, .8, Scalar.White, 2);
for (var i = 0; i < 3; i++) { yolo.Detect(frame); hand.Detect(frame); }
var timer = Stopwatch.StartNew();
for (var i = 0; i < 10; i++) { yolo.Detect(frame); hand.Detect(frame); }
timer.Stop();
var engine = new SopEngine();
var config = SopConfigLoader.Parse("sop:\n name: Linux smoke\n settings:\n auto_reset_on_complete: false\n steps:\n - id: 1\n name: Clock\n detection:\n method: time_elapsed\n duration_ms: 1\n");
engine.Load(config); engine.Start(); Thread.Sleep(10);
engine.ProcessFrame(new FrameResult { Size = (640, 480), Timestamp = DateTime.Now });
if (engine.State != EngineState.Completed) throw new Exception("SOP 状态机测试失败");
Cv2.ImWrite("workspace/smoke-frame.png", frame);
// A real video file exercises the same videoio backend used by the desktop player.
using (var writer = new VideoWriter("workspace/smoke-input.avi", FourCC.MJPG, 10, frame.Size()))
{
if (!writer.IsOpened()) throw new Exception("录像编码器不可用");
for (var i = 0; i < 30; i++) writer.Write(frame);
}
using var capture = new VideoCapture("workspace/smoke-input.avi");
using var read = new Mat();
if (!capture.Read(read) || read.Empty()) throw new Exception("视频读取失败");
var result = new { passed = true, opencv = Cv2.GetVersionString(), yoloClasses = yolo.ClassNames.Count,
backend = "CPU", threads = Environment.GetEnvironmentVariable("SOPHELPER_CPU_THREADS"),
meanBlankFrameMs = timer.Elapsed.TotalMilliseconds / 10, sop = engine.State.ToString(), video = "PASS" };
var json = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("workspace/self-test.json", json);
Console.WriteLine(json); return 0;
}
catch (Exception ex) { Console.Error.WriteLine(ex); return 1; }
}
}

View File

@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<AssemblyName>SopHelper.Linux</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../SopHelper.Linux.Engine/SopHelper.Linux.Engine.csproj" />
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.22" />
<Content Include="../../configs/sop/*.yaml" Link="configs/sop/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../SopHelper.App/Assets/bws.svg" Link="Assets/bws.svg" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -7,6 +7,6 @@
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.Engine/SopHelper.Engine.csproj" />
<ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
</ItemGroup>
</Project>

View File

@ -6,8 +6,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="../../src/SopHelper.Engine/Common/Types.cs" Link="Types.cs" />
<Compile Include="../../src/SopHelper.Engine/Inference/HandednessStabilizer.cs" Link="HandednessStabilizer.cs" />
<Compile Include="../../src/SopHelper.Engine/Inference/HandednessDecoder.cs" Link="HandednessDecoder.cs" />
<Compile Include="../../src/SopHelper.CrossPlatform.Engine/Common/Types.cs" Link="Types.cs" />
<Compile Include="../../src/SopHelper.CrossPlatform.Engine/Inference/HandednessStabilizer.cs" Link="HandednessStabilizer.cs" />
<Compile Include="../../src/SopHelper.CrossPlatform.Engine/Inference/HandednessDecoder.cs" Link="HandednessDecoder.cs" />
</ItemGroup>
</Project>

View File

@ -1,401 +0,0 @@
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Sop;
using SopHelper.VVMs.RecipeEditor;
using Point = System.Windows.Point;
using Rect = System.Windows.Rect;
using Size = System.Windows.Size;
internal static class Program
{
[STAThread]
private static int Main(string[] args)
{
var app = new Application();
app.Resources.MergedDictionaries.Add(new ResourceDictionary
{
Source = new Uri("pack://application:,,,/SopHelper;component/Themes/Styles.xaml"),
});
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
var run = CheckAsync(args);
_ = run.ContinueWith(_ => app.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background));
Dispatcher.Run();
try { run.GetAwaiter().GetResult(); return 0; }
catch (Exception ex) { Console.Error.WriteLine(ex); return 1; }
}
private static async Task CheckAsync(string[] args)
{
var imageSize = new Size(4000, 2000);
var display = RegionCanvas.FitImage(new Size(800, 600), imageSize);
if (display != new Rect(0, 100, 800, 400)) throw new Exception("横向留白计算错误");
var first = RegionCanvas.ToImage(new Point(160, 180), display, imageSize);
var last = RegionCanvas.ToImage(new Point(640, 420), display, imageSize);
var bounds = RegionCanvas.PixelBounds(last, first, imageSize);
if (bounds != new Int32Rect(800, 400, 2400, 1200)) throw new Exception("反向画框或像素换算错误");
var clipped = RegionCanvas.ToImage(new Point(900, -50), display, imageSize);
if (clipped != new Point(4000, 0)) throw new Exception("边界截取错误");
var portrait = RegionCanvas.FitImage(new Size(800, 600), new Size(1000, 2000));
if (portrait != new Rect(250, 0, 300, 600)) throw new Exception("纵向图像留白计算错误");
Console.WriteLine("PASS: 原图像素换算、横竖图留白、反向画框及越界截取");
await CheckCompletionResetAsync();
var saveDirectory = Path.Combine(Path.GetTempPath(), "SopHelper-save-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(saveDirectory);
var savePath = Path.Combine(saveDirectory, "repeat-save.yaml");
var notifications = new List<string>();
var saveVm = new RecipeEditorViewModel();
try
{
saveVm.OnDialogOpened(new DialogParameters
{
{ "directory", saveDirectory }, { "new", true },
{ "onSaved", new Action<string>(notifications.Add) },
});
saveVm.Recipe.Name = "首次保存";
saveVm.Recipe.FileName = "repeat-save";
saveVm.Recipe.Settings.ExposureTimeUs = 12500;
var editedRecipe = saveVm.Recipe;
// 未注册关闭监听器:保存如果仍尝试关闭弹窗,就不能正常完成。
saveVm.SaveCommand.Execute();
if (!saveVm.SaveStatus.StartsWith("已保存") || saveVm.Recipe.CanEditFileName ||
saveVm.Title != "编辑配方 - repeat-save.yaml" || notifications.Count != 1 ||
SopConfigLoader.Load(savePath).Sop.Name != "首次保存")
throw new Exception("首次保存后的状态或文件不正确:" + string.Join(";", saveVm.Warnings));
saveVm.Recipe.Name = "继续修改并保存";
var restoredSettings = new RecipeSettingsNode();
restoredSettings.CopyFrom(SopConfigLoader.Load(savePath).Sop.Settings);
if (restoredSettings.ExposureTimeUs != 12500) throw new Exception("曝光保存重开丢失");
saveVm.Recipe.Settings.ExposureTimeUs = null;
saveVm.SaveCommand.Execute();
if (!saveVm.SaveStatus.StartsWith("已保存") || !ReferenceEquals(editedRecipe, saveVm.Recipe) ||
notifications.Count != 2 || notifications.Any(name => name != "repeat-save.yaml") ||
SopConfigLoader.Load(savePath).Sop.Name != "继续修改并保存" || Directory.GetFiles(saveDirectory).Length != 1)
throw new Exception("连续保存未更新原配方文件");
if (SopConfigLoader.Load(savePath).Sop.Settings.ExposureTimeUs is not null)
throw new Exception("曝光留空后仍保留旧值");
saveVm.Recipe.Settings.ExposureTimeUs = -1;
saveVm.SaveCommand.Execute();
if (!saveVm.Warnings.Any(w => w.Contains("相机曝光必须大于"))) throw new Exception("允许保存无效曝光值");
saveVm.Recipe.Settings.ExposureTimeUs = null;
Console.WriteLine("PASS: 保存不请求关闭、编辑状态保留、新建转为编辑、连续保存更新同一文件并通知主页");
saveVm.Recipe.AddStepCommand.Execute();
if (!saveVm.Warnings.Any(w => w.Contains("未设置完成条件")))
throw new Exception("新增空步骤未提示设置完成条件");
var stepView = new RecipeEditor { DataContext = saveVm };
stepView.Measure(new Size(1020, 720));
stepView.Arrange(new Rect(0, 0, 1020, 720));
stepView.UpdateLayout();
var editorTabs = Descendants(stepView).OfType<TabControl>().Single();
editorTabs.SelectedItem = editorTabs.Items.OfType<TabItem>().Single(t => Equals(t.Header, "检测模型"));
stepView.UpdateLayout();
var exposureInput = (TextBox)stepView.FindName("CameraExposureInput");
exposureInput.Text = "18000";
exposureInput.GetBindingExpression(TextBox.TextProperty)!.UpdateSource();
if (saveVm.Recipe.Settings.ExposureTimeUs != 18000) throw new Exception("检测模型页曝光输入未绑定配方");
saveVm.Recipe.Settings.ExposureTimeUs = null;
editorTabs.SelectedIndex = 0;
stepView.UpdateLayout();
SelectMethod(stepView, ConditionMethod.TimeElapsed);
if (saveVm.Warnings.Any(w => w.Contains("未设置完成条件")))
throw new Exception("选择方法后缺少判定的提示未实时更新");
saveVm.SaveCommand.Execute();
if (SopConfigLoader.Load(savePath).Sop.Steps.Single().Detection?.Method != ConditionMethod.TimeElapsed)
throw new Exception("新增步骤在界面选择方法后未保存");
SelectMethod(stepView, "");
if (!saveVm.Warnings.Any(w => w.Contains("未设置完成条件")))
throw new Exception("清空方法后未重新提示设置完成条件");
saveVm.SaveCommand.Execute();
var reopenedVm = new RecipeEditorViewModel();
reopenedVm.OnDialogOpened(new DialogParameters
{
{ "path", savePath }, { "config", SopConfigLoader.Load(savePath) },
});
stepView.DataContext = reopenedVm;
stepView.UpdateLayout();
SelectMethod(stepView, ConditionMethod.TimeElapsed);
reopenedVm.SaveCommand.Execute();
if (SopConfigLoader.Load(savePath).Sop.Steps.Single().Detection?.Method != ConditionMethod.TimeElapsed)
throw new Exception("未配置判定的步骤重新打开后选择方法无法保存");
var reopenedAgain = RecipeNode.From(SopConfigLoader.Load(savePath), "repeat-save", false);
if (reopenedAgain.SelectedStep?.Detection?.Method != ConditionMethod.TimeElapsed)
throw new Exception("保存后再次打开丢失判定方法");
var addRule = Descendants(stepView).OfType<Button>().Single(b => Equals(b.Content, "加违规规则"));
if (addRule.Command is null || !addRule.Command.CanExecute(addRule.CommandParameter))
throw new Exception("新增违规规则按钮未绑定可执行命令");
addRule.Command.Execute(addRule.CommandParameter);
stepView.UpdateLayout();
var rule = reopenedVm.Recipe.SelectedStep!.ViolationRules.Items.Single();
rule.Type = ViolationType.ObjectRemoved;
rule.Description = "必留物品被拿走";
rule.Severity = 2;
reopenedVm.SaveCommand.Execute();
var savedRule = SopConfigLoader.Load(savePath).Sop.Steps.Single().ViolationRules.Single();
if (savedRule.Type != ViolationType.ObjectRemoved || savedRule.Description != "必留物品被拿走" || savedRule.Severity != 2)
throw new Exception("新增违规规则未正确保存");
var removeRule = Descendants(stepView).OfType<Button>().Single(b =>
ReferenceEquals(b.DataContext, rule) && Equals(b.Content, "删"));
if (removeRule.Command is null) throw new Exception("违规规则删除按钮未绑定命令");
removeRule.Command.Execute(removeRule.CommandParameter);
reopenedVm.SaveCommand.Execute();
if (SopConfigLoader.Load(savePath).Sop.Steps.Single().ViolationRules.Count != 0)
throw new Exception("删除违规规则未正确保存");
Console.WriteLine("PASS: 界面新增违规规则、编辑字段、保存回读和删除");
foreach (var requiredAtEnd in new[] { true, false })
{
var buttonText = requiredAtEnd ? "加完成必需物品" : "加必留物品";
var addItem = Descendants(stepView).OfType<Button>().Single(b => Equals(b.Content, buttonText));
if (addItem.Command is null || !addItem.Command.CanExecute(addItem.CommandParameter))
throw new Exception(buttonText + "按钮未绑定可执行命令");
addItem.Command.Execute(addItem.CommandParameter);
stepView.UpdateLayout();
var step = reopenedVm.Recipe.SelectedStep!;
var item = (requiredAtEnd ? step.RequiredObjects : step.MustKeep).Items.Single();
var input = Descendants(stepView).OfType<TextBox>().Single(b => ReferenceEquals(b.DataContext, item));
input.SetCurrentValue(TextBox.TextProperty, "part_a");
reopenedVm.SaveCommand.Execute();
var loadedStep = RecipeNode.From(SopConfigLoader.Load(savePath), "repeat-save", false).SelectedStep!;
if ((requiredAtEnd ? loadedStep.RequiredObjects : loadedStep.MustKeep).Items.Single().Text != "part_a")
throw new Exception(buttonText + "在界面输入后未保存或重新打开后丢失");
var deleteItem = Descendants(stepView).OfType<Button>().Single(b =>
ReferenceEquals(b.DataContext, item) && Equals(b.Content, "删"));
if (deleteItem.Command is null) throw new Exception(buttonText + "缺少删除命令");
deleteItem.Command.Execute(deleteItem.CommandParameter);
reopenedVm.SaveCommand.Execute();
var savedStep = SopConfigLoader.Load(savePath).Sop.Steps.Single();
if ((requiredAtEnd ? savedStep.RequiredObjects : savedStep.MustKeep).Count != 0)
throw new Exception(buttonText + "删除未保存");
}
Console.WriteLine("PASS: 完成必需物品和必留物品的界面新增、文字编辑、保存重开及删除");
reopenedVm.OnDialogClosed();
Console.WriteLine("PASS: 新增步骤和重新打开的空判定步骤,通过界面选择方法后均可保存");
}
finally
{
saveVm.OnDialogClosed();
if (File.Exists(savePath)) File.Delete(savePath);
Directory.Delete(saveDirectory);
}
var node = new RegionNode();
node.PropertyChanged += (_, _) =>
{
if ((node.X1, node.Y1, node.X2, node.Y2) != (800, 400, 3200, 1600))
throw new Exception("坐标更新通知发出时数据不完整");
};
node.SetBounds(bounds);
var config = new SopConfig();
config.Sop.Name = "画框标定";
config.Sop.Settings.ExposureTimeUs = 12000;
config.Sop.Regions["work"] = new RegionDef { X1 = 200, Y1 = 150, X2 = 950, Y2 = 650, Name = "操作区域", Color = "#00B8D4" };
using var fake = new CaptureCamera();
using var real = args.Contains("--hardware") ? new CameraService() : null;
var camera = (ICameraService?)real ?? fake;
var cameraInfo = real is null ? new CameraInfo { Index = 0, Name = "测试图像" } :
(await real.EnumerateAsync()).First(c => c.Kind == CameraKind.Hikvision);
var vm = new RecipeEditorViewModel();
vm.OnDialogOpened(new DialogParameters
{
{ "config", config }, { "new", true }, { "cameraService", camera }, { "cameraInfo", cameraInfo },
});
vm.CaptureImageCommand.Execute();
var deadline = DateTime.UtcNow.AddSeconds(20);
while (vm.IsCapturing && DateTime.UtcNow < deadline) await Task.Delay(20);
if (vm.IsCapturing || vm.PreviewImage is null) throw new Exception("取图失败:" + vm.PreviewStatus);
if (!vm.PreviewImage.IsFrozen || camera.IsConnected || camera.IsGrabbing) throw new Exception("图像未冻结或取图后未释放相机");
if (real is null && fake.ExposureAtStart != 12000) throw new Exception("区域取图前未应用配方曝光");
if (real is null)
{
var starts = fake.StartCount;
fake.RejectExposure = true;
vm.CaptureImageCommand.Execute();
while (vm.IsCapturing) await Task.Delay(20);
if (!vm.PreviewStatus.Contains("失败") || fake.StartCount != starts || fake.IsConnected)
throw new Exception("曝光设置失败后仍采集或未释放相机");
fake.RejectExposure = false;
}
if (vm.Recipe.SelectedRegion is null) throw new Exception("区域未自动选中");
vm.Recipe.SelectedRegion.SetBounds(new Int32Rect(200, 150, 750, 500));
var saved = vm.Recipe.ToConfig().Sop.Regions["work"];
if ((saved.X1, saved.Y1, saved.X2, saved.Y2) != (200, 150, 950, 650)) throw new Exception("画框坐标未写入配方");
Console.WriteLine($"PASS: {vm.PreviewImage.PixelWidth}x{vm.PreviewImage.PixelHeight} 取图、资源释放和坐标写回配方");
var view = new RecipeEditor { DataContext = vm };
view.Measure(new Size(1020, 720));
view.Arrange(new Rect(0, 0, 1020, 720));
view.UpdateLayout();
var tabs = Descendants(view).OfType<TabControl>().Single();
tabs.SelectedIndex = 1;
view.UpdateLayout();
var canvas = Descendants(view).OfType<RegionCanvas>().Single();
if (!ReferenceEquals(canvas.Image, vm.PreviewImage) || !ReferenceEquals(canvas.SelectedRegion, vm.Recipe.SelectedRegion))
throw new Exception("画布绑定错误");
if (canvas.ActualWidth < 400 || canvas.ActualHeight < 200) throw new Exception("图像预览区域过小");
var normalCanvasSize = canvas.RenderSize;
var previewSize = new Size(vm.PreviewImage.PixelWidth, vm.PreviewImage.PixelHeight);
var normalImage = RegionCanvas.FitImage(normalCanvasSize, previewSize);
var dialogStyle = Dialog.GetWindowStyle(view);
var host = new DialogWindow { Style = dialogStyle, Content = view, Opacity = 0, ShowActivated = false, ShowInTaskbar = false };
if (host.SizeToContent != SizeToContent.Manual || host.ResizeMode != ResizeMode.CanResize ||
host.HorizontalContentAlignment != HorizontalAlignment.Stretch ||
host.VerticalContentAlignment != VerticalAlignment.Stretch)
throw new Exception("配方弹窗未配置为可缩放并拉伸内容");
// 用较大的客户区模拟最大化,验证整个弹窗内容链路,而非只检查画布自身。
host.Width = 1920;
host.Height = 1080;
host.Show();
host.UpdateLayout();
if (view.ActualWidth < host.ActualWidth - 100 || view.ActualHeight < host.ActualHeight - 100 ||
canvas.ActualWidth <= normalCanvasSize.Width || canvas.ActualHeight <= normalCanvasSize.Height)
throw new Exception($"放大弹窗后编辑内容或图像画布未扩展:内容 {view.RenderSize},画布 {canvas.RenderSize},窗口 {host.RenderSize}");
var enlargedImage = RegionCanvas.FitImage(canvas.RenderSize, previewSize);
var enlargedCanvasSize = canvas.RenderSize;
if (enlargedImage.Width <= normalImage.Width || enlargedImage.Height <= normalImage.Height)
throw new Exception("放大弹窗后图像显示尺寸未增大");
var enlargedPoint = new Point(enlargedImage.X + enlargedImage.Width / 4,
enlargedImage.Y + enlargedImage.Height / 4);
var mappedPoint = RegionCanvas.ToImage(enlargedPoint, enlargedImage, previewSize);
if ((mappedPoint - new Point(previewSize.Width / 4, previewSize.Height / 4)).Length > 0.001)
throw new Exception("放大后的原图坐标换算错误");
Console.WriteLine($"PASS: 弹窗内容随尺寸扩展,画布 {normalCanvasSize} → {canvas.RenderSize},图像等比放大且坐标正确");
host.Width = 1040;
host.Height = 760;
host.UpdateLayout();
if (canvas.ActualWidth >= enlargedCanvasSize.Width || canvas.ActualHeight >= enlargedCanvasSize.Height)
throw new Exception("还原窗口后画布未缩小");
if (args.FirstOrDefault(a => a.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) is string output)
{
var bitmap = new RenderTargetBitmap(1020, 720, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(view);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var file = File.Create(output);
encoder.Save(file);
}
host.Content = null;
host.Close();
vm.OnDialogClosed();
Console.WriteLine("PASS: 区域页布局、预览与所选区域绑定");
}
private static async Task CheckCompletionResetAsync()
{
foreach (var autoReset in new[] { false, true })
{
var config = new SopConfig();
config.Sop.Settings.AutoResetOnComplete = autoReset;
config.Sop.Settings.ResetDelaySec = 1;
foreach (var id in new[] { 3, 8 })
config.Sop.Steps.Add(new StepDef
{
Id = id, Name = $"步骤{id}",
Detection = new StepCondition { Method = ConditionMethod.TimeElapsed, DurationMs = 5 },
});
var engine = new SopEngine();
var snapshots = new Dictionary<int, StepSnapshot>();
engine.StepSnapshotChanged += snapshot => snapshots[snapshot.StepId] = snapshot;
var completions = 0;
engine.Completed += () =>
{
completions++;
if (snapshots.Count != 2 || snapshots.Values.Any(s => s.IsMet || s.IsCurrent))
throw new Exception("整轮完成时未清除所有完成状态或当前步骤高亮");
};
engine.Load(config);
engine.Start();
var frame = new SopHelper.Engine.Common.FrameResult();
await Task.Delay(20);
engine.ProcessFrame(frame);
if (!snapshots[3].IsMet || engine.CurrentStep?.Id != 8)
throw new Exception("最后一步完成前应保留已完成步骤状态");
await Task.Delay(20);
engine.ProcessFrame(frame);
if (completions != 1 || engine.State != EngineState.Completed)
throw new Exception("整轮完成事件或状态不正确");
if (autoReset)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
while (engine.State == EngineState.Completed && DateTime.UtcNow < deadline)
await Task.Delay(20);
}
else engine.Reset();
if (engine.State != EngineState.Running || engine.CurrentStep?.Id != 3 ||
snapshots.Values.Any(s => s.IsMet) || !snapshots[3].IsCurrent || snapshots[8].IsCurrent)
throw new Exception("复位后状态未清空或未回到第一步");
await Task.Delay(20);
engine.ProcessFrame(frame);
if (!snapshots[3].IsMet || engine.CurrentStep?.Id != 8)
throw new Exception("复位后第一步计时条件未重新开始");
engine.Start();
if (snapshots.Values.Any(s => s.IsMet)) throw new Exception("重新开始后残留完成状态");
}
Console.WriteLine("PASS: 末步完成立即清空状态,手动/自动复位与重新开始无残留,首步计时可再次完成");
}
private static void SelectMethod(RecipeEditor view, string method)
{
var combo = Descendants(view).OfType<ComboBox>().Single(c =>
System.Windows.Data.BindingOperations.GetBinding(c, ComboBox.SelectedItemProperty)?.Path.Path == "Detection.Method");
combo.SetCurrentValue(ComboBox.SelectedItemProperty, method);
view.UpdateLayout();
}
private static IEnumerable<DependencyObject> Descendants(DependencyObject parent)
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
yield return child;
foreach (var next in Descendants(child)) yield return next;
}
}
}
internal sealed class CaptureCamera : ICameraService
{
public bool RejectExposure { get; set; }
public int StartCount { get; private set; }
public double? ExposureAtStart { get; private set; }
private double? _exposure;
public Task SetExposureTimeAsync(double microseconds)
{
if (!IsConnected || IsGrabbing || RejectExposure) throw new InvalidOperationException("测试曝光设置失败");
_exposure = microseconds;
return Task.CompletedTask;
}
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
#pragma warning disable CS0067
public event Action<string>? Error;
#pragma warning restore CS0067
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo>());
public Task<bool> ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
public async Task<bool> StartAsync()
{
StartCount++;
ExposureAtStart = _exposure;
IsGrabbing = true;
await Task.Run(() =>
{
using var mat = new Mat(900, 1600, MatType.CV_8UC3, new Scalar(48, 41, 34));
for (var x = 0; x < mat.Width; x += 100) Cv2.Line(mat, new OpenCvSharp.Point(x, 0), new OpenCvSharp.Point(x, mat.Height), new Scalar(70, 65, 60));
for (var y = 0; y < mat.Height; y += 100) Cv2.Line(mat, new OpenCvSharp.Point(0, y), new OpenCvSharp.Point(mat.Width, y), new Scalar(70, 65, 60));
using var frame = new CameraFrame { FrameId = 1, Timestamp = DateTime.Now, Bgr = mat.Clone() };
FrameArrived?.Invoke(frame);
});
return true;
}
public void Stop() => IsGrabbing = false;
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
public void Dispose() => Disconnect();
}

View File

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj" />
</ItemGroup>
</Project>

View File

@ -1,102 +0,0 @@
using System.Windows;
using Prism.DryIoc;
using Prism.Ioc;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
internal static class Program
{
[STAThread]
private static int Main(string[] args)
{
var app = new ShutdownProbe(args.Contains("--hardware"));
var result = app.Run();
if (result != 0) return result;
return app.VerifyAfterExitAsync().GetAwaiter().GetResult();
}
}
/// <summary>不创建窗口;使用正式服务注册及 WPF Shutdown → App.OnExit 链路。</summary>
internal sealed class ShutdownProbe(bool hardware) : SopHelper.App
{
private ICameraService _camera = null!;
private DetectionPipeline _pipeline = null!;
private CameraInfo? _selected;
private bool _exitObserved;
protected override async void OnStartup(StartupEventArgs e)
{
ShutdownMode = ShutdownMode.OnExplicitShutdown;
var registry = new DryIocContainerExtension();
RegisterTypes(registry);
_camera = registry.Resolve<ICameraService>();
_pipeline = registry.Resolve<DetectionPipeline>();
_camera.Error += message => Console.WriteLine(message);
Exit += (_, _) =>
{
// App.OnExit 必须在调用 WPF 的 Exit 事件之前完成释放。
_exitObserved = true;
if (_camera.IsConnected || _camera.IsGrabbing)
throw new InvalidOperationException("WPF Exit 时相机仍在连接/采集");
};
try
{
if (hardware)
{
_selected = (await _camera.EnumerateAsync()).FirstOrDefault(c => c.Kind == CameraKind.Hikvision)
?? throw new InvalidOperationException("未发现海康相机");
Console.WriteLine($"设备:{_selected.Name}");
if (!await _camera.ConnectAsync(_selected)) throw new InvalidOperationException("连接失败");
var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_camera.FrameArrived += frame =>
{
if (!frame.Bgr.Empty() && frame.Bgr.Channels() == 3) ready.TrySetResult();
};
if (!await _pipeline.StartAsync()) throw new InvalidOperationException("启动失败");
await ready.Task.WaitAsync(TimeSpan.FromSeconds(10));
Console.WriteLine("PASS: 真实采集中直接调用 Application.Shutdown");
}
// 不主动 Stop/Disconnect/Dispose,不依赖页面 Destroy。
Shutdown();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
Shutdown(1);
}
}
internal async Task<int> VerifyAfterExitAsync()
{
try
{
if (!_exitObserved) throw new InvalidOperationException("未触发 WPF Exit");
try
{
await _camera.StartAsync();
throw new InvalidOperationException("退出后服务仍允许启动");
}
catch (ObjectDisposedException) { }
_camera.Dispose();
_pipeline.Dispose();
Console.WriteLine("PASS: WPF 退出已释放服务,重复释放安全,退出后禁止重新启动");
if (_selected is not null)
{
// 原进程仍存活,证明是显式关闭设备,而非进程结束后的系统回收。
using var reopened = new HikvisionCameraService();
reopened.Error += Console.WriteLine;
if (!await reopened.ConnectAsync(_selected))
throw new InvalidOperationException("退出清理后同一进程仍无法重新打开相机");
Console.WriteLine("PASS: 原进程退出清理后立即重新打开同一海康相机");
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
return 1;
}
}
}

View File

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj" />
</ItemGroup>
</Project>

View File

@ -1,214 +0,0 @@
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using SopHelper.Training;
using SopHelper.Engine.Camera;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
var root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../../workspace/camera-smoke-" + Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(root);
var app = new SopHelper.App(); app.InitializeComponent();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(app.Dispatcher));
try
{
TestRecorder(root);
TestViewModel(root);
TestCloseWhileConnecting(root);
TestStalledCamera(root);
TestSopStopReleasesCamera();
Console.WriteLine("PASS: recording and camera lifecycle checks; artifacts: " + root);
return 0;
}
catch (Exception e) { Console.Error.WriteLine(e); return 1; }
}
private static void Require(bool condition, string error) { if (!condition) throw new Exception(error); }
private static void TestSopStopReleasesCamera()
{
using var camera = new FakeCamera();
using var pipeline = new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
var sop = new SopHelper.VVMs.SopPage.SopPageViewModel(camera, pipeline,
new SopHelper.Engine.Sop.SopEngine(), null!);
try
{
for (var cycle = 0; cycle < 2; cycle++)
{
camera.ConnectAsync(new CameraInfo { Name = "Test" }).GetAwaiter().GetResult();
PumpUntil(() => sop.IsConnected);
sop.IsRunning = true;
sop.StartStopCommand.Execute();
PumpUntil(() => sop.CanSelectCamera);
Require(!camera.IsConnected && !camera.IsGrabbing && !sop.IsConnected && !sop.IsRunning,
"SOP stop retained camera ownership and would block recording");
}
Console.WriteLine("PASS: repeated SOP stop releases device and clears recording entry blockers");
}
finally { sop.Destroy(); }
}
private static void PumpUntil(Func<bool> ready, int timeout = 5000)
{
var watch = Stopwatch.StartNew();
while (!ready())
{
if (watch.ElapsedMilliseconds > timeout) throw new TimeoutException("Dispatcher test timed out");
Application.Current.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
Thread.Sleep(10);
}
Application.Current.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
}
private static void TestRecorder(string root)
{
using var recorder = new VideoRecorder();
using var frame = new Mat(120, 160, MatType.CV_8UC3, new Scalar(30,50,80));
var watch = Stopwatch.StartNew();
var path = recorder.Start(Path.Combine(root, "中文录像目录"), frame);
watch.Restart();
for (var i = 0; i < 10; i++)
{
Thread.Sleep(100); frame.SetTo(new Scalar(30+i*10,50,80)); recorder.Write(frame);
}
var result = recorder.Stop()!;
Require(!recorder.IsRecording && recorder.Stop() == null, "Stop must be idempotent");
Require(Math.Abs(result.Duration.TotalSeconds - watch.Elapsed.TotalSeconds) < 0.2, "Recording duration differs from wall clock");
using (var capture = new VideoCapture(path))
using (var decoded = new Mat())
{
Require(capture.IsOpened() && capture.Read(decoded), "AVI could not be decoded");
Require(decoded.Width == 160 && decoded.Height == 120, "Video resolution changed");
Require(Cv2.Mean(decoded).Val0 > 20, "Video pixels missing");
Require(Math.Abs(capture.Get(VideoCaptureProperties.Fps) - 30) < 0.01, "Unexpected recording FPS");
Require((long)capture.Get(VideoCaptureProperties.FrameCount) == result.Frames, "AVI frame count mismatch");
}
var second = recorder.Start(root, frame); recorder.Stop();
Require(second != path && File.Exists(path) && File.Exists(second), "New recording overwrote the previous file");
recorder.Start(root, frame);
using var changed = new Mat(80, 160, MatType.CV_8UC3, Scalar.Black);
try { recorder.Write(changed); throw new Exception("Resolution change accepted"); }
catch (IOException) { }
Require(!recorder.IsRecording, "Failed writer was not finalized");
using var odd = new Mat(121,161,MatType.CV_8UC3,Scalar.Black);
try { recorder.Start(root, odd); throw new Exception("Odd size accepted"); }
catch (ArgumentException) { }
var file = Path.Combine(root, "not-a-directory"); File.WriteAllText(file, "test");
try { recorder.Start(file, frame); throw new Exception("File accepted as directory"); }
catch (IOException) { }
Require(!recorder.IsRecording, "Failed start changed recording state");
Console.WriteLine($"PASS: real MJPEG encode/decode, Chinese directory, {result.Frames} frames / {result.Duration.TotalSeconds:F2}s, pacing, repeated recordings, failure cleanup");
}
private static void TestViewModel(string root)
{
var fake = new FakeCamera();
var model = new CameraViewModel(fake, root);
Require(!model.RecordCommand.CanExecute(), "Recording enabled without camera");
model.RefreshCommand.Execute(); PumpUntil(() => !model.IsBusy);
Require(model.Cameras.Count == 1 && model.SelectedCamera != null, "Camera list failed");
model.PreviewCommand.Execute(); PumpUntil(() => !model.IsBusy && model.Preview != null);
Require(model.IsPreviewing, "Live preview failed");
model.SaveDirectory = Path.Combine(root,"自选保存位置");
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && model.IsRecording);
Require(!model.CanChooseCamera && !model.CanChangeDirectory && !model.RefreshCommand.CanExecute(), "Controls should be locked while recording");
Thread.Sleep(300);
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && !model.IsRecording);
Require(model.IsPreviewing && model.CanChangeDirectory, "Stop recording should preserve preview and unlock the directory");
var firstRecording = model.LastRecording;
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && model.IsRecording);
Require(model.LastRecording != firstRecording, "Second recording should use a new filename");
Thread.Sleep(300);
var window = new CameraWindow(model);
Render(window, Path.Combine(root, "camera-preview.png"));
var shutdown = model.ShutdownAsync(); PumpUntil(() => shutdown.IsCompleted); shutdown.GetAwaiter().GetResult();
Require(fake.Disposed && !model.IsRecording && !model.IsPreviewing, "Closing did not release camera/recording");
using (var capture = new VideoCapture(model.LastRecording)) Require(capture.IsOpened() && capture.Get(VideoCaptureProperties.FrameCount) > 0, "Close did not finalize AVI");
var closed = false; window.Closed += (_, _) => closed = true;
window.Close(); PumpUntil(() => closed);
var secondFake = new FakeCamera();
var reopened = new CameraViewModel(secondFake, root);
Require(reopened.SaveDirectory == model.SaveDirectory, "Selected recording directory not persisted");
var task = reopened.ShutdownAsync(); PumpUntil(() => task.IsCompleted); task.GetAwaiter().GetResult();
Console.WriteLine("PASS: WPF live preview, directory persistence, record state, closing while recording, preview rendering");
}
private static void TestCloseWhileConnecting(string root)
{
var fake = new FakeCamera { ConnectDelay = 200 };
var model = new CameraViewModel(fake, root) { SelectedCamera = new CameraInfo { Name = "Test" } };
model.PreviewCommand.Execute();
var close = model.ShutdownAsync(); PumpUntil(() => close.IsCompleted); close.GetAwaiter().GetResult();
Require(fake.Disposed && fake.Starts == 0 && !fake.IsGrabbing, "Pending connect reopened camera after close");
Console.WriteLine("PASS: close waits for pending connection and prevents late acquisition");
}
private static void TestStalledCamera(string root)
{
var fake = new FakeCamera();
var model = new CameraViewModel(fake, root) { SelectedCamera = new CameraInfo { Name = "Test" } };
model.PreviewCommand.Execute(); PumpUntil(() => !model.IsBusy && model.Preview != null);
model.RecordCommand.Execute(); PumpUntil(() => model.IsRecording && !model.IsBusy);
fake.PauseFrames = true;
PumpUntil(() => !model.IsRecording, 4000);
Require(!model.RecordCommand.CanExecute(), "Recording enabled on stale preview");
var close = model.ShutdownAsync(); PumpUntil(() => close.IsCompleted); close.GetAwaiter().GetResult();
using var capture = new VideoCapture(model.LastRecording);
Require(capture.IsOpened(), "Stall did not finalize recording");
Console.WriteLine("PASS: stalled camera automatically stops and finalizes recording, stale preview cannot start a new recording");
}
private static void Render(CameraWindow window, string path)
{
var content = (FrameworkElement)window.Content; window.Content = null;
content.DataContext = window.Model; content.Margin = new Thickness(0);
content.Width = 1044; content.Height = 744;
content.Measure(new System.Windows.Size(1044,744)); content.Arrange(new System.Windows.Rect(0,0,1044,744));
content.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle); content.UpdateLayout();
var bitmap = new RenderTargetBitmap(1044,744,96,96,PixelFormats.Pbgra32); bitmap.Render(content);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path); encoder.Save(stream);
}
}
internal sealed class FakeCamera : ICameraService
{
private CancellationTokenSource? _stop;
private Task? _loop;
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public bool Disposed { get; private set; }
public int ConnectDelay { get; init; }
public int Starts { get; private set; }
public volatile bool PauseFrames;
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error { add { } remove { } }
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo> { new() { Name = "模拟 UVC 相机 · 160×120" } });
public async Task<bool> ConnectAsync(CameraInfo info)
{
if (ConnectDelay > 0) await Task.Delay(ConnectDelay);
IsConnected = true; ConnectionChanged?.Invoke(true); return true;
}
public Task<bool> StartAsync()
{
Starts++; IsGrabbing = true; _stop = new CancellationTokenSource();
var token = _stop.Token;
_loop = Task.Run(() =>
{
long index = 0;
while (!token.IsCancellationRequested)
{
if (PauseFrames) { Thread.Sleep(33); continue; }
var image = new Mat(120,160,MatType.CV_8UC3,new Scalar(40,60,80));
Cv2.Rectangle(image, new OpenCvSharp.Rect(30,25,90,60), new Scalar(170,190,210), -1);
using var frame = new CameraFrame { Bgr = image, FrameId = index++, Timestamp = DateTime.Now };
FrameArrived?.Invoke(frame); Thread.Sleep(33);
}
});
return Task.FromResult(true);
}
public void Stop() { _stop?.Cancel(); _loop?.GetAwaiter().GetResult(); _stop?.Dispose(); _stop = null; _loop = null; IsGrabbing = false; }
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
public void Dispose() { Disconnect(); Disposed = true; }
}

View File

@ -1,4 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0-windows</TargetFramework><UseWPF>true</UseWPF><PlatformTarget>x64</PlatformTarget><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj"/></ItemGroup>
</Project>

View File

@ -1,77 +0,0 @@
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Prism.Ioc;
using Prism.Navigation.Regions;
using SopHelper.Models;
using SopHelper.Training;
internal static class Program
{
[STAThread]
private static int Main(string[] args)
{
var app = new ShellProbe(args.Contains("--idle"));
app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/SopHelper;component/Themes/Styles.xaml", UriKind.Relative) });
return app.Run();
}
}
internal sealed class ShellProbe(bool idle) : SopHelper.App
{
private MainViewModel? _trainer;
protected override void OnInitialized()
{
base.OnInitialized();
Dispatcher.BeginInvoke(async () =>
{
try
{
var navigation = Container.Resolve<NavigationModel>();
var regions = Container.Resolve<IRegionManager>();
if (!navigation.Pages.Any(p => p.ViewName == nameof(TrainingPage))) throw new Exception("Training navigation missing");
navigation.SelectedIndex = 1;
await Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
var page = regions.Regions[NavigationModel.ContentRegion].ActiveViews.OfType<TrainingPage>().Single();
_trainer = (MainViewModel)page.DataContext;
if (_trainer.Root != Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../..")))
throw new Exception("Training root does not resolve to SopHelper repository");
if (!File.Exists(Path.Combine(_trainer.Root, "tools", "worker.py"))) throw new Exception("Worker missing");
_trainer.Label = "导航状态检查";
navigation.SelectedIndex = 0;
navigation.SelectedIndex = 1;
var restored = regions.Regions[NavigationModel.ContentRegion].ActiveViews.OfType<TrainingPage>().Single();
if (!ReferenceEquals(page, restored) || ((MainViewModel)restored.DataContext).Label != "导航状态检查")
throw new Exception("Navigation lost training state");
MainWindow.UpdateLayout();
var image = new RenderTargetBitmap((int)MainWindow.ActualWidth, (int)MainWindow.ActualHeight, 96, 96, PixelFormats.Pbgra32);
image.Render(MainWindow);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image));
using (var output = File.Create(Path.Combine(Path.GetTempPath(), "sophelper-training-shell.png"))) encoder.Save(output);
Console.WriteLine("PASS: actual Prism shell, navigation registration, DI, repository root, page state retained, shell render");
// Start a real background worker, navigate away, then close the shell.
if (!idle) _trainer.DoctorCommand.Execute();
navigation.SelectedIndex = 0;
MainWindow.Close();
}
catch (Exception error)
{
Console.Error.WriteLine(error);
Shutdown(1);
}
});
}
protected override void OnExit(ExitEventArgs e)
{
if (_trainer?.IsBusy == true)
{
Console.Error.WriteLine("FAIL: shell exited before training worker stopped");
e.ApplicationExitCode = 1;
}
else Console.WriteLine("PASS: shell close after navigating away waits for worker cancellation");
base.OnExit(e);
}
}

View File

@ -1,4 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0-windows</TargetFramework><UseWPF>true</UseWPF><PlatformTarget>x64</PlatformTarget><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj"/></ItemGroup>
</Project>

View File

@ -1 +1 @@
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup><ItemGroup><ProjectReference Include="../../src/SopHelper.Engine/SopHelper.Engine.csproj"/></ItemGroup></Project>
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup><ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj"/></ItemGroup></Project>

View File

@ -1,78 +0,0 @@
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SopHelper.Training;
using SopHelper.Engine.Training;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
var app = new SopHelper.App(); app.InitializeComponent();
var model = new MainViewModel(new WorkerClient());
if (args.Length > 0) model.Load(Path.GetFullPath(args[0]));
var window = new TrainingPage(model, null);
var content = (FrameworkElement)window.Content;
window.Content = null;
content.DataContext = model;
content.Margin = new Thickness(0);
content.Width = 1404; content.Height = 844;
content.Measure(new Size(1404, 844)); content.Arrange(new Rect(0, 0, 1404, 844)); content.UpdateLayout();
content.Dispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
content.UpdateLayout();
if (content.ActualWidth < 1000) throw new Exception("Layout failed");
var image = new RenderTargetBitmap(1440, 880, 96, 96, PixelFormats.Pbgra32);
var visual = new DrawingVisual();
using (var drawing = visual.RenderOpen()) drawing.DrawRectangle(new SolidColorBrush(Color.FromRgb(16,24,32)), null, new Rect(0,0,1440,880));
image.Render(visual); image.Render(content);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image));
var output = args.Length > 1 ? args[1] : Path.Combine(Path.GetTempPath(), "parttrainer-ui.png");
using (var stream = File.Create(output)) encoder.Save(stream);
Console.WriteLine("PASS: WPF resources, view model, preview layout rendered to " + output);
if (model.Project != null)
{
model.DrawBox([1,1,Math.Min(100,model.Project.Width), Math.Min(100,model.Project.Height)]);
if (model.SelectedFrame?.Prompt != true || model.SelectedFrame.Status != "reviewed") throw new Exception("Manual seed not saved");
model.ExcludeCommand.Execute();
if (model.SelectedFrame?.Box != null || model.SelectedFrame?.Prompt != false) throw new Exception("Exclusion failed");
model.NextCommand.Execute();
Console.WriteLine("PASS: manual correction persistence, exclusion, frame navigation");
}
TestApproveAll();
return 0;
}
private static void TestApproveAll()
{
var root = Path.Combine(Path.GetTempPath(), "parttrainer-review-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
var bitmap = BitmapSource.Create(100,80,96,96,PixelFormats.Bgr24,null,new byte[100*80*3],300);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var image = File.Create(Path.Combine(root,"frame.png"))) encoder.Save(image);
var states = new[] { "auto", "auto", "excluded", "reviewed", "auto", "unlabeled" };
var project = new TrainingProject { FilePath = Path.Combine(root,"project.json"), Width = 100, Height = 80 };
for (var index = 0; index < states.Length; index++)
project.Frames.Add(new FrameAnnotation { Index = index, Image = "frame.png", Status = states[index],
Box = index == 1 ? null : [10,10,50,50], Prompt = index == 4 });
project.Save();
var weights = Path.Combine(root,"runs","test","weights","best.pt");
File.WriteAllText(Path.Combine(root,"latest-model.json"), System.Text.Json.JsonSerializer.Serialize(new
{ weights, runDirectory = Path.Combine(root,"runs","test"), metrics = new Dictionary<string,double> { ["metrics/mAP50(B)"] = 0.75 } }));
var model = new MainViewModel(new WorkerClient()); model.Load(project.FilePath,1);
if (model.LatestWeights != weights || !model.TrainingMetrics.Contains("0.7500")) throw new Exception("Training result did not reload");
model.ApproveAllCommand.Execute();
var saved = TrainingProject.Load(project.FilePath);
var expected = new[] { "reviewed", "auto", "excluded", "reviewed", "reviewed", "unlabeled" };
if (!saved.Frames.Select(f => f.Status).SequenceEqual(expected)) throw new Exception("Batch review changed incorrect frames");
if (saved.Frames[0].Prompt || !saved.Frames[4].Prompt) throw new Exception("Batch review changed keyframe flags");
if (model.SelectedFrame?.Index != 1 || model.Frames[0].Display.Contains("待复核")) throw new Exception("Batch review did not refresh selection/list");
model.ApproveAllCommand.Execute();
if (model.Status != "没有带目标框的待复核帧") throw new Exception("Repeated batch review did not handle empty batch");
Console.WriteLine("PASS: batch review persistence, pending boxes only, negative/excluded/unlabeled preservation, keyframe preservation, selection refresh, repeated click");
}
finally { Directory.Delete(root,true); }
}
}

View File

@ -1 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0-windows</TargetFramework><UseWPF>true</UseWPF><PlatformTarget>x64</PlatformTarget><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup><ItemGroup><ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj"/></ItemGroup></Project>

View File

@ -7,6 +7,6 @@
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.Engine/SopHelper.Engine.csproj" />
<ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
</ItemGroup>
</Project>

View File

@ -6,7 +6,7 @@ $ErrorActionPreference='Stop'
$repo=Split-Path $PSScriptRoot -Parent
if (!$OutputRoot) { $OutputRoot=Join-Path $repo 'artifacts/avalonia' }
$project=Join-Path $repo 'src/SopHelper.Avalonia/SopHelper.Avalonia.csproj'
$sources=@('src/SopHelper.Avalonia','src/SopHelper.CrossPlatform.Engine','src/SopHelper.Engine') | ForEach-Object {
$sources=@('src/SopHelper.Avalonia','src/SopHelper.CrossPlatform.Engine') | ForEach-Object {
Get-ChildItem (Join-Path $repo $_) -Recurse -File | Where-Object {
$_.FullName -notmatch '[\\/](bin|obj)[\\/]' -and $_.Extension -in '.cs','.axaml','.csproj'
}

View File

@ -20,7 +20,7 @@ SopHelper 是通用 SOP 程序。程序负责配方执行、条件判定、操
## 当前程序基础
- Engine 与 WPF 应用分离,已有相机采集、目标与手部检测、顺序步骤状态机。
- 共享 Engine 与 Avalonia 应用分离,已有相机采集、目标与手部检测、顺序步骤状态机。
- YAML 配方已有名称、业务版本、步骤、区域、模型、标准工时和单个步骤完成条件。
- 已有开始、暂停、复位、整轮完成、超时和必留物异常、文本日志、手动快照。
- 训练模块已有相机录像、视频导入、标注与训练能力,可复用底层能力。