diff --git a/AVALONIA.md b/AVALONIA.md
index 04e69df..77f25cd 100644
--- a/AVALONIA.md
+++ b/AVALONIA.md
@@ -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 库名,
diff --git a/LINUX.md b/LINUX.md
index f70d848..28ae3f0 100644
--- a/LINUX.md
+++ b/LINUX.md
@@ -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 运行时:
diff --git a/README.md b/README.md
index a980fb3..4a3bc52 100644
--- a/README.md
+++ b/README.md
@@ -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)。
diff --git a/SopHelper.Linux.slnx b/SopHelper.Linux.slnx
deleted file mode 100644
index ac2b058..0000000
--- a/SopHelper.Linux.slnx
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/SopHelper.slnx b/SopHelper.slnx
deleted file mode 100644
index 93846e4..0000000
--- a/SopHelper.slnx
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/src/SopHelper.App/App.xaml b/src/SopHelper.App/App.xaml
deleted file mode 100644
index 82e167e..0000000
--- a/src/SopHelper.App/App.xaml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/App.xaml.cs b/src/SopHelper.App/App.xaml.cs
deleted file mode 100644
index d8e63bb..0000000
--- a/src/SopHelper.App/App.xaml.cs
+++ /dev/null
@@ -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;
-
-///
-/// 应用程序入口,负责初始化 Prism 框架和注册组件(启动链照搬 plcsharp)
-///
-public partial class App
-{
- private ICameraService? _camera;
- private DetectionPipeline? _pipeline;
- private Engine.Training.WorkerClient? _trainingWorker;
-
- ///
- /// 注册应用程序所需的类型和服务
- ///
- protected override void RegisterTypes(IContainerRegistry containerRegistry)
- {
- RegisterEvents(); // 捕获全局异常
-
- // 注册带 [Model] 特性的类,单例
- foreach (var model in from t in Assembly.GetExecutingAssembly().GetTypes()
- where t.GetCustomAttribute() is not null
- select t)
- {
- _ = containerRegistry.RegisterSingleton(model);
- }
-
- // 注册带 [NavigationPage] 特性的 View 到导航
- foreach (var view in from t in Assembly.GetExecutingAssembly().GetTypes()
- where t.GetCustomAttribute() is not null
- select t)
- {
- containerRegistry.RegisterForNavigation(view, view.Name);
- }
-
- _ = containerRegistry.RegisterSingleton();
-
- // 引擎层三件套。它们在 SopHelper.Engine 程序集里,上面的 [Model] 反射扫描只覆盖本程序集,
- // 所以必须显式注册,否则 SOP 页 ViewModel 的构造注入解析不出来。
- // 共享硬件和推理由应用持有;页面销毁和容器回收不能代替应用退出清理。
- _camera = new CameraService();
- _pipeline = new DetectionPipeline(_camera);
- containerRegistry.RegisterInstance(_camera);
- containerRegistry.RegisterInstance(_pipeline);
- _ = containerRegistry.RegisterSingleton();
-
- // ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册
- _ = containerRegistry.RegisterSingleton();
- _trainingWorker = new Engine.Training.WorkerClient();
- containerRegistry.RegisterInstance(_trainingWorker);
- containerRegistry.RegisterSingleton();
-
- // 配方编辑器弹窗(SOP 页「编辑」「新建」按钮弹出)
- containerRegistry.RegisterDialog("RecipeEditorDialog");
- }
-
- ///
- /// 创建Shell
- ///
- protected override Window CreateShell()
- {
- var navigate = Container.Resolve();
-
- // 反射收集导航页
- foreach (var view in from t in Assembly.GetExecutingAssembly().GetTypes()
- where t.GetCustomAttribute() is not null
- orderby t.GetCustomAttribute()!.Index
- select t)
- {
- var page = view.GetCustomAttribute()!;
-
- var item = Container.Resolve();
- item.ViewName = page.ViewName;
- item.DisplayName = page.DisplayName;
- navigate.Pages.Add(item);
- }
-
- var window = Container.Resolve();
-
- // 默认页:区域要等窗口加载后才注册,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);
- }
- }
-
- ///
- /// 自动寻找ViewModel并绑定到View,要求ViewModel命名为View的全名加上ViewModel,比如MainWindow的ViewModel命名为MainWindowViewModel
- ///
- 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);
- });
- }
-
- ///
- /// 捕获全局异常
- ///
- 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
- {
- // 日志失败不影响主流程
- }
- }
-}
diff --git a/src/SopHelper.App/Assets/BellwetherLogo.xaml b/src/SopHelper.App/Assets/BellwetherLogo.xaml
deleted file mode 100644
index d7dfec9..0000000
--- a/src/SopHelper.App/Assets/BellwetherLogo.xaml
+++ /dev/null
@@ -1,167 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/Core/Prism/CoreAttribute.cs b/src/SopHelper.App/Core/Prism/CoreAttribute.cs
deleted file mode 100644
index 29ab00c..0000000
--- a/src/SopHelper.App/Core/Prism/CoreAttribute.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-namespace SopHelper.Core.Prism;
-
-///
-/// 标志此特性的类会被注册为单例(照搬 plcsharp 约定)
-///
-[AttributeUsage(AttributeTargets.Class)]
-public class ModelAttribute : Attribute
-{
-}
-
-///
-/// 标志此特性的 View 会被注册到导航列表
-///
-[AttributeUsage(AttributeTargets.Class)]
-public class NavigationPageAttribute : Attribute
-{
- ///
- /// 视图名称(导航用)
- ///
- public string ViewName { get; set; } = "";
-
- ///
- /// Display名称
- ///
- public string DisplayName { get; set; } = "";
-
- ///
- /// 排序序号
- ///
- public int Index { get; set; }
-}
-
-///
-/// 标志此特性的类会被注册为弹出窗口
-///
-[AttributeUsage(AttributeTargets.Class)]
-public class DialogAttribute : Attribute
-{
-}
diff --git a/src/SopHelper.App/Core/Prism/MessageEvent.cs b/src/SopHelper.App/Core/Prism/MessageEvent.cs
deleted file mode 100644
index b0b9370..0000000
--- a/src/SopHelper.App/Core/Prism/MessageEvent.cs
+++ /dev/null
@@ -1,61 +0,0 @@
-using Prism.Events;
-
-namespace SopHelper.Core.Prism;
-
-///
-/// 全局消息事件(照搬 plcsharp:模块间解耦都走事件聚合器)
-///
-public class MessageEvent : PubSubEvent
-{
-}
-
-///
-/// 消息内容
-///
-public struct Message
-{
- ///
- /// 消息目标
- ///
- public string Target { get; set; }
-
- ///
- /// 消息
- ///
- public string Content { get; set; }
-
- ///
- /// 消息类型 1 记录 2 弹出 3 弹出并记录
- ///
- public ShowType Type { get; set; }
-
- ///
- /// 级别
- ///
- public MsgLevel Level { get; set; }
-}
-
-///
-/// 显示方式
-///
-public enum ShowType
-{
- /// 仅记录日志
- Log = 1,
-
- /// 仅提示
- Show = 2,
-
- /// 提示并记录
- Both = 3,
-}
-
-///
-/// 消息级别
-///
-public enum MsgLevel
-{
- Info,
- Warn,
- Error,
-}
diff --git a/src/SopHelper.App/Core/Prism/ModelBase.cs b/src/SopHelper.App/Core/Prism/ModelBase.cs
deleted file mode 100644
index 1562226..0000000
--- a/src/SopHelper.App/Core/Prism/ModelBase.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using Prism.Events;
-using Prism.Ioc;
-using Prism.Mvvm;
-
-namespace SopHelper.Core.Prism;
-
-///
-/// 模型Base
-///
-public class ModelBase : BindableBase
-{
- ///
- /// 事件聚合器
- ///
- protected readonly IEventAggregator _eventAggregator;
-
- ///
- /// DI 容器
- ///
- protected readonly IContainerExtension _container;
-
- ///
- /// 模型Base
- ///
- public ModelBase(IContainerExtension container, IEventAggregator ea)
- {
- _container = container;
- _eventAggregator = ea;
-
- _eventAggregator.GetEvent().Subscribe(OnMessage, ThreadOption.PublisherThread, true);
-
- AppDomain.CurrentDomain.ProcessExit += OnExit;
- }
-
- ///
- /// 收到消息(子类覆写做本模块的落库/统计)
- ///
- protected virtual void OnMessage(Message message)
- {
- }
-
- ///
- /// 进程退出(子类覆写做释放)
- ///
- protected virtual void OnExit(object? sender, EventArgs e)
- {
- }
-}
diff --git a/src/SopHelper.App/Core/Prism/NavigateItem.cs b/src/SopHelper.App/Core/Prism/NavigateItem.cs
deleted file mode 100644
index 4af4c70..0000000
--- a/src/SopHelper.App/Core/Prism/NavigateItem.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using Prism.Mvvm;
-
-namespace SopHelper.Core.Prism;
-
-///
-/// Navigate项
-///
-public class NavigateItem : BindableBase
-{
- private string _viewName = "";
-
- ///
- /// 视图名称
- ///
- public string ViewName
- {
- get { return _viewName; }
- set { SetProperty(ref _viewName, value); }
- }
-
- private string _displayName = "";
-
- ///
- /// Display名称
- ///
- public string DisplayName
- {
- get { return _displayName; }
- set { SetProperty(ref _displayName, value); }
- }
-}
diff --git a/src/SopHelper.App/Core/Prism/ViewModelBase.cs b/src/SopHelper.App/Core/Prism/ViewModelBase.cs
deleted file mode 100644
index 40777ed..0000000
--- a/src/SopHelper.App/Core/Prism/ViewModelBase.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using Prism.Mvvm;
-using Prism.Navigation;
-
-namespace SopHelper.Core.Prism;
-
-///
-/// 视图模型Base
-///
-public abstract class ViewModelBase : BindableBase, IDestructible
-{
- ///
- /// Destroy
- ///
- public virtual void Destroy()
- {
- }
-}
diff --git a/src/SopHelper.App/Models/NavigationModel.cs b/src/SopHelper.App/Models/NavigationModel.cs
deleted file mode 100644
index 06027e9..0000000
--- a/src/SopHelper.App/Models/NavigationModel.cs
+++ /dev/null
@@ -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;
-
-///
-/// Navigate模型
-///
-[Model]
-public class NavigationModel : ModelBase
-{
- private readonly IRegionManager _regionManager;
-
- ///
- /// Navigate模型
- ///
- public NavigationModel(IContainerExtension container, IEventAggregator ea, IRegionManager regionManager)
- : base(container, ea)
- {
- _regionManager = regionManager;
- }
-
- private ObservableCollection _pages = [];
-
- ///
- /// 导航页列表(shell 侧栏绑定)
- ///
- public ObservableCollection Pages
- {
- get { return _pages; }
- set { SetProperty(ref _pages, value); }
- }
-
- private NavigateItem? _target;
-
- ///
- /// 当前页
- ///
- public NavigateItem? Target
- {
- get { return _target; }
- set { SetProperty(ref _target, value); }
- }
-
- private int _selectedIndex = -1;
-
- ///
- /// 侧栏选中索引
- ///
- public int SelectedIndex
- {
- get { return _selectedIndex; }
- set
- {
- if (!SetProperty(ref _selectedIndex, value)) return;
- if (value >= 0 && value < Pages.Count) Navigate(Pages[value].ViewName);
- }
- }
-
- ///
- /// 导航到指定页
- ///
- 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);
- }
-
- ///
- /// 内容区名(shell 与导航的唯一约定)
- ///
- public const string ContentRegion = "ContentRegion";
-}
diff --git a/src/SopHelper.App/SopHelper.App.csproj b/src/SopHelper.App/SopHelper.App.csproj
deleted file mode 100644
index f18c1b7..0000000
--- a/src/SopHelper.App/SopHelper.App.csproj
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
- WinExe
- net8.0-windows
- true
- latest
- enable
- enable
- x64
- AnyCPU;x64
- true
- SopHelper
- SopHelper
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/Themes/Styles.xaml b/src/SopHelper.App/Themes/Styles.xaml
deleted file mode 100644
index 11b291f..0000000
--- a/src/SopHelper.App/Themes/Styles.xaml
+++ /dev/null
@@ -1,332 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/Training/AnnotationCanvas.cs b/src/SopHelper.App/Training/AnnotationCanvas.cs
deleted file mode 100644
index 2a1f54a..0000000
--- a/src/SopHelper.App/Training/AnnotationCanvas.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using System.Windows;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-
-namespace SopHelper.Training;
-
-/// Aspect-fit preview with original-image coordinates, including letterbox offsets.
-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? 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); }
-}
diff --git a/src/SopHelper.App/Training/CameraViewModel.cs b/src/SopHelper.App/Training/CameraViewModel.cs
deleted file mode 100644
index 6866ac5..0000000
--- a/src/SopHelper.App/Training/CameraViewModel.cs
+++ /dev/null
@@ -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 _commands = [];
-
- public ObservableCollection 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 action, Func canExecute)
- {
- var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute);
- _commands.Add(command); return command;
- }
- private async Task PerformAsync(Func 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;
- }
- }
- }
-}
diff --git a/src/SopHelper.App/Training/CameraWindow.xaml b/src/SopHelper.App/Training/CameraWindow.xaml
deleted file mode 100644
index 7764281..0000000
--- a/src/SopHelper.App/Training/CameraWindow.xaml
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/Training/CameraWindow.xaml.cs b/src/SopHelper.App/Training/CameraWindow.xaml.cs
deleted file mode 100644
index 43acc05..0000000
--- a/src/SopHelper.App/Training/CameraWindow.xaml.cs
+++ /dev/null
@@ -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(); });
- }
-}
diff --git a/src/SopHelper.App/Training/MainViewModel.cs b/src/SopHelper.App/Training/MainViewModel.cs
deleted file mode 100644
index 8d6ac12..0000000
--- a/src/SopHelper.App/Training/MainViewModel.cs
+++ /dev/null
@@ -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 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? 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 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 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 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 = "设置文件不可读,已使用默认配置"; }
- }
-}
diff --git a/src/SopHelper.App/Training/Styles.xaml b/src/SopHelper.App/Training/Styles.xaml
deleted file mode 100644
index 5a32764..0000000
--- a/src/SopHelper.App/Training/Styles.xaml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/Training/TrainingPage.xaml b/src/SopHelper.App/Training/TrainingPage.xaml
deleted file mode 100644
index 26248b1..0000000
--- a/src/SopHelper.App/Training/TrainingPage.xaml
+++ /dev/null
@@ -1,76 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/Training/TrainingPage.xaml.cs b/src/SopHelper.App/Training/TrainingPage.xaml.cs
deleted file mode 100644
index c3cbcd8..0000000
--- a/src/SopHelper.App/Training/TrainingPage.xaml.cs
+++ /dev/null
@@ -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();
-}
diff --git a/src/SopHelper.App/VVMs/MainWindow/MainWindow.xaml b/src/SopHelper.App/VVMs/MainWindow/MainWindow.xaml
deleted file mode 100644
index 738d0f5..0000000
--- a/src/SopHelper.App/VVMs/MainWindow/MainWindow.xaml
+++ /dev/null
@@ -1,77 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/VVMs/MainWindow/MainWindow.xaml.cs b/src/SopHelper.App/VVMs/MainWindow/MainWindow.xaml.cs
deleted file mode 100644
index 3a6e9bd..0000000
--- a/src/SopHelper.App/VVMs/MainWindow/MainWindow.xaml.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System.Windows;
-
-namespace SopHelper.VVMs.MainWindow;
-
-///
-/// 主窗口(shell:侧导航 + 内容区)
-///
-public partial class MainWindow : Window
-{
- ///
- /// 主窗口
- ///
- public MainWindow()
- {
- InitializeComponent();
- }
-}
diff --git a/src/SopHelper.App/VVMs/MainWindow/MainWindowViewModel.cs b/src/SopHelper.App/VVMs/MainWindow/MainWindowViewModel.cs
deleted file mode 100644
index 5eac70b..0000000
--- a/src/SopHelper.App/VVMs/MainWindow/MainWindowViewModel.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using Prism.Commands;
-using Prism.Mvvm;
-using SopHelper.Models;
-
-namespace SopHelper.VVMs.MainWindow;
-
-///
-/// Main窗口视图模型
-///
-public class MainWindowViewModel : BindableBase
-{
- private readonly NavigationModel _navigation;
-
- ///
- /// Main窗口视图模型
- ///
- public MainWindowViewModel(NavigationModel navigation)
- {
- _navigation = navigation;
- }
-
- private string _title = "SopHelper";
-
- ///
- /// 标题
- ///
- public string Title
- {
- get { return _title; }
- set { SetProperty(ref _title, value); }
- }
-
- ///
- /// 导航模型(侧栏绑定)
- ///
- public NavigationModel Navigation => _navigation;
-
-
-}
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs
deleted file mode 100644
index abe63c7..0000000
--- a/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs
+++ /dev/null
@@ -1,1011 +0,0 @@
-using System.Collections.ObjectModel;
-using System.Windows.Input;
-using System.Windows.Media;
-using Prism.Commands;
-using SopHelper.Core.Prism;
-using SopHelper.Engine.Sop;
-
-namespace SopHelper.VVMs.RecipeEditor;
-
-///
-/// 编辑器自己的可观察节点。配方模型(SopHelper.Engine)是纯数据类、不带 INPC,
-/// 引擎层不该为 UI 引这套接口,所以绑定层在这一侧,保存时整体映射回 SopConfig。
-///
-public abstract class EditorNode : BindableBase
-{
-}
-
-///
-/// 可被"可编辑列表"删除的行
-///
-public interface IRemovable
-{
- /// 删除自己(由所属列表注入)
- ICommand? RemoveCommand { get; set; }
-}
-
-///
-/// 字符串列表项(YAML 的 classes / must_keep / required_objects)。
-/// 不能直接绑 string——string 不实现 INPC,TwoWay 写不回集合项。
-///
-public class TextItem : EditorNode, IRemovable
-{
- private string _text = "";
-
- /// 文本
- public string Text
- {
- get { return _text; }
- set { SetProperty(ref _text, value); }
- }
-
- ///
- public ICommand? RemoveCommand { get; set; }
-
- ///
- public override string ToString() => Text;
-}
-
-///
-/// 可增删的行列表(类别名、必在物料、违规规则都用它)
-///
-public class EditableList : EditorNode where T : EditorNode, IRemovable, new()
-{
- /// 列表标题
- public string Title { get; init; } = "";
-
- /// 行
- public ObservableCollection Items { get; } = [];
-
- /// 加一行
- public DelegateCommand AddCommand { get; }
-
- /// 删一行
- public DelegateCommand RemoveCommand { get; }
-
- ///
- /// 可增删的行列表
- ///
- public EditableList()
- {
- AddCommand = new DelegateCommand(() =>
- {
- var item = new T { RemoveCommand = RemoveCommand };
- Items.Add(item);
- });
-
- RemoveCommand = new DelegateCommand(item =>
- {
- if (item is not null) Items.Remove(item);
- });
- }
-}
-
-///
-/// sop 根节点
-///
-public class RecipeNode : EditorNode
-{
- private string _fileName = "";
- private bool _isNew;
- private string _name = "";
- private string _version = "1.0";
- private string _description = "";
- private bool _hasModel;
- private RecipeModelNode? _model;
- private RegionNode? _selectedRegion;
- private StepNode? _selectedStep;
-
- ///
- /// 配方根节点
- ///
- public RecipeNode()
- {
- Methods =
- [
- "",
- ConditionMethod.TimeElapsed,
- ConditionMethod.HandInRegion,
- ConditionMethod.HandMove,
- ConditionMethod.HandNearObject,
- ConditionMethod.ObjectPresent,
- ConditionMethod.ObjectInZone,
- ConditionMethod.PersonPresent,
- ];
-
- Hands = ["any", "left", "right"];
- ViolationTypes = [ViolationType.Timeout, ViolationType.ObjectRemoved];
-
- AddRegionCommand = new DelegateCommand(() => { AddRegion(); Changed?.Invoke(); });
- RemoveRegionCommand = new DelegateCommand(node => { RemoveRegion(node); Changed?.Invoke(); }, node => node is not null);
-
- AddStepCommand = new DelegateCommand(() => { AddStep(); Changed?.Invoke(); });
- RemoveStepCommand = new DelegateCommand(node => { RemoveStep(node); Changed?.Invoke(); }, node => node is not null);
- MoveStepUpCommand = new DelegateCommand(node => { MoveStepUp(node); Changed?.Invoke(); }, node => node is not null && Steps.Any(s => s.Id < node.Id));
- MoveStepDownCommand = new DelegateCommand(node => { MoveStepDown(node); Changed?.Invoke(); }, node => node is not null && Steps.Any(s => s.Id > node.Id));
- }
-
- /// 加区域
- public DelegateCommand AddRegionCommand { get; }
-
- /// 删区域
- public DelegateCommand RemoveRegionCommand { get; }
-
- /// 加步骤
- public DelegateCommand AddStepCommand { get; }
-
- /// 删步骤
- public DelegateCommand RemoveStepCommand { get; }
-
- /// 步骤上移
- public DelegateCommand MoveStepUpCommand { get; }
-
- /// 步骤下移
- public DelegateCommand MoveStepDownCommand { get; }
-
- /// 列表结构变了(ViewModel 借此重跑校验)
- public event Action? Changed;
-
- /// 文件名(不含扩展名;新建时可填,之后按它落盘)
- public string FileName
- {
- get { return _fileName; }
- set { SetProperty(ref _fileName, value); }
- }
-
- /// 新建(尚未落盘)
- public bool IsNew
- {
- get { return _isNew; }
- private set
- {
- if (!SetProperty(ref _isNew, value)) return;
- RaisePropertyChanged(nameof(CanEditFileName));
- }
- }
-
- /// 文件名是否可编辑(只有新建能改——SOP 页按文件名选配方,已存在的改名等于换个配方)
- public bool CanEditFileName
- {
- get { return IsNew; }
- }
-
- internal void MarkSaved(string fileName)
- {
- FileName = fileName;
- IsNew = false;
- }
-
- /// 配方名(sop.name)
- public string Name
- {
- get { return _name; }
- set { SetProperty(ref _name, value); }
- }
-
- /// 版本(sop.version)
- public string Version
- {
- get { return _version; }
- set { SetProperty(ref _version, value); }
- }
-
- /// 说明(sop.description)
- public string Description
- {
- get { return _description; }
- set { SetProperty(ref _description, value); }
- }
-
- /// 全局设置(sop.settings)
- public RecipeSettingsNode Settings { get; } = new();
-
- /// 区域(sop.regions,键 = 配方里引用的区域名)
- public ObservableCollection Regions { get; } = [];
-
- /// 步骤(sop.steps)
- public ObservableCollection Steps { get; } = [];
-
- /// 是否配置检测模型(不勾就不写 sop.model 节点)
- public bool HasModel
- {
- get { return _hasModel; }
- set
- {
- if (!SetProperty(ref _hasModel, value)) return;
-
- // 勾上给一个可编辑的模型节点,取消勾选就丢弃
- _model = value ? _model ?? new RecipeModelNode() : null;
- RaisePropertyChanged(nameof(Model));
- }
- }
-
- /// 模型定义(HasModel=false 时为 null)
- public RecipeModelNode? Model
- {
- get { return _model; }
- private set { SetProperty(ref _model, value); }
- }
-
- /// 当前编辑的区域
- public RegionNode? SelectedRegion
- {
- get { return _selectedRegion; }
- set { SetProperty(ref _selectedRegion, value); }
- }
-
- /// 当前编辑的步骤
- public StepNode? SelectedStep
- {
- get { return _selectedStep; }
- set { SetProperty(ref _selectedStep, value); }
- }
-
- /// method 下拉候选(空串 = 本步不写判定条件)
- public IReadOnlyList Methods { get; }
-
- /// hand 下拉候选
- public IReadOnlyList Hands { get; }
-
- /// 违规类型下拉候选
- public IReadOnlyList ViolationTypes { get; }
-
- /// 区域名下拉候选(含空项,表示该字段不引用区域)
- public IReadOnlyList RegionNames
- {
- get
- {
- var names = Regions.Select(r => r.Key).Where(k => !string.IsNullOrWhiteSpace(k)).ToList();
- names.Insert(0, "");
- return names;
- }
- }
-
- /// 加区域
- public RegionNode AddRegion()
- {
- var node = new RegionNode
- {
- Key = $"region{Regions.Count + 1}",
- Name = "新区域",
- X1 = 100,
- Y1 = 100,
- X2 = 400,
- Y2 = 400,
- };
-
- node.Renamed += OnRegionRenamed;
- Regions.Add(node);
- SelectedRegion = node;
-
- return node;
- }
-
- /// 删区域(条件里引用了它的步骤会清掉引用,避免留下悬空引用)
- public void RemoveRegion(RegionNode? node)
- {
- if (node is null) return;
-
- Regions.Remove(node);
- node.Renamed -= OnRegionRenamed;
-
- foreach (var step in Steps.Where(s => s.Detection is not null && References(s.Detection, node.Key)))
- ClearRegionReferences(step.Detection!, node.Key);
-
- SelectedRegion = Regions.FirstOrDefault();
- }
-
- /// 加步骤(Id 取当前最大 +1,执行顺序按 Id 升序)
- public StepNode AddStep()
- {
- var node = new StepNode
- {
- Id = Steps.Count == 0 ? 1 : Steps.Max(s => s.Id) + 1,
- Name = "新步骤",
- Detection = new ConditionNode(),
- };
-
- Steps.Add(node);
- SelectedStep = node;
-
- return node;
- }
-
- /// 删步骤
- public void RemoveStep(StepNode? node)
- {
- if (node is null) return;
-
- Steps.Remove(node);
- SelectedStep = Steps.FirstOrDefault();
- }
-
- /// 上移(与上一个交换 Id——执行顺序就是 Id 升序)
- public void MoveStepUp(StepNode? node)
- {
- if (node is null) return;
-
- var prev = Steps.Where(s => s.Id < node.Id).OrderByDescending(s => s.Id).FirstOrDefault();
- if (prev is null) return;
-
- (node.Id, prev.Id) = (prev.Id, node.Id);
- ResortSteps();
- }
-
- /// 下移
- public void MoveStepDown(StepNode? node)
- {
- if (node is null) return;
-
- var next = Steps.Where(s => s.Id > node.Id).OrderBy(s => s.Id).FirstOrDefault();
- if (next is null) return;
-
- (node.Id, next.Id) = (next.Id, node.Id);
- ResortSteps();
- }
-
- ///
- /// 区域键名变了 → 同步条件里的引用。不做这一步,改个区域名就得把每个引用它的步骤手改一遍。
- ///
- private void OnRegionRenamed(string from, string to)
- {
- if (string.Equals(from, to, StringComparison.OrdinalIgnoreCase)) return;
-
- foreach (var step in Steps)
- {
- var condition = step.Detection;
- if (condition is null) continue;
-
- if (string.Equals(condition.Region, from, StringComparison.OrdinalIgnoreCase)) condition.Region = to;
- if (string.Equals(condition.FromRegion, from, StringComparison.OrdinalIgnoreCase)) condition.FromRegion = to;
- if (string.Equals(condition.ToRegion, from, StringComparison.OrdinalIgnoreCase)) condition.ToRegion = to;
- }
-
- RaisePropertyChanged(nameof(RegionNames));
- }
-
- /// 按 Id 重排(保持选中项)
- private void ResortSteps()
- {
- var selected = SelectedStep;
-
- var ordered = Steps.OrderBy(s => s.Id).ToList();
- Steps.Clear();
- foreach (var step in ordered) Steps.Add(step);
-
- SelectedStep = selected;
- }
-
- private static bool References(ConditionNode condition, string key)
- => new[] { condition.Region, condition.FromRegion, condition.ToRegion }
- .Any(n => string.Equals(n, key, StringComparison.OrdinalIgnoreCase));
-
- private static void ClearRegionReferences(ConditionNode condition, string key)
- {
- if (string.Equals(condition.Region, key, StringComparison.OrdinalIgnoreCase)) condition.Region = "";
- if (string.Equals(condition.FromRegion, key, StringComparison.OrdinalIgnoreCase)) condition.FromRegion = "";
- if (string.Equals(condition.ToRegion, key, StringComparison.OrdinalIgnoreCase)) condition.ToRegion = "";
- }
-
- ///
- /// 配方 → 编辑器节点
- ///
- public static RecipeNode From(SopConfig config, string fileName, bool isNew)
- {
- var node = new RecipeNode
- {
- FileName = System.IO.Path.GetFileNameWithoutExtension(fileName),
- IsNew = isNew,
- Name = config.Sop.Name,
- Version = config.Sop.Version,
- Description = config.Sop.Description,
- };
-
- node.Settings.CopyFrom(config.Sop.Settings);
-
- foreach (var (key, def) in config.Sop.Regions)
- {
- var region = new RegionNode { Key = key };
- region.CopyFrom(def);
- region.Renamed += node.OnRegionRenamed;
- node.Regions.Add(region);
- }
-
- foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
- {
- var stepNode = new StepNode
- {
- Id = step.Id,
- Name = step.Name,
- Description = step.Description,
- Timeout = step.Timeout,
- StandardDurationMs = step.StandardDurationMs,
- };
-
- foreach (var item in step.MustKeep) stepNode.MustKeep.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.MustKeep.RemoveCommand });
- foreach (var item in step.RequiredObjects) stepNode.RequiredObjects.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.RequiredObjects.RemoveCommand });
-
- if (step.Detection is not null) stepNode.Detection = ConditionNode.From(step.Detection);
-
- foreach (var rule in step.ViolationRules)
- stepNode.ViolationRules.Items.Add(ViolationRuleNode.From(rule, stepNode.ViolationRules.RemoveCommand));
-
- node.Steps.Add(stepNode);
- }
-
- if (config.Sop.Model is not null)
- {
- node.HasModel = true;
- node.Model?.CopyFrom(config.Sop.Model);
- }
-
- node.SelectedStep = node.Steps.FirstOrDefault();
- node.SelectedRegion = node.Regions.FirstOrDefault();
-
- return node;
- }
-
- ///
- /// 编辑器节点 → 配方(全新构造一份,不动原对象)
- ///
- public SopConfig ToConfig()
- {
- var config = new SopConfig();
-
- config.Sop.Name = Name;
- config.Sop.Version = Version;
- config.Sop.Description = Description;
-
- Settings.CopyTo(config.Sop.Settings);
-
- foreach (var region in Regions.Where(r => !string.IsNullOrWhiteSpace(r.Key)))
- {
- var def = new RegionDef { Name = region.Name, Description = region.Description, Color = region.Color };
- region.CopyTo(def);
- config.Sop.Regions[region.Key.Trim()] = def;
- }
-
- foreach (var step in Steps.OrderBy(s => s.Id))
- {
- var def = new StepDef
- {
- Id = step.Id,
- Name = step.Name,
- Description = step.Description,
- Timeout = step.Timeout,
- StandardDurationMs = step.StandardDurationMs,
- };
-
- def.MustKeep.AddRange(step.MustKeep.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
- def.RequiredObjects.AddRange(step.RequiredObjects.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
-
- if (step.Detection is not null && !string.IsNullOrWhiteSpace(step.Detection.Method))
- def.Detection = step.Detection.ToCondition();
-
- foreach (var rule in step.ViolationRules.Items.Where(r => !string.IsNullOrWhiteSpace(r.Type)))
- def.ViolationRules.Add(rule.ToRule());
-
- config.Sop.Steps.Add(def);
- }
-
- // 只有勾了模型才写 sop.model:留一个 path 为空的节点会让校验里"需要模型"那几条提醒失灵
- if (HasModel && Model is not null)
- {
- var def = new ModelDef { Path = Model.Path, InputSize = Model.InputSize };
- def.Classes.AddRange(Model.Classes.Items.Select(c => c.Text).Where(c => !string.IsNullOrWhiteSpace(c)));
- config.Sop.Model = def;
- }
-
- return config;
- }
-}
-
-///
-/// sop.settings
-///
-public class RecipeSettingsNode : EditorNode
-{
- private float _confidenceThreshold = 0.6f;
- private int _stableFrames = 5;
- private float _positionTolerance = 20f;
- private bool _enableTimeoutDetection = true;
- private bool _autoResetOnComplete = true;
- private int _resetDelaySec = 1;
- private int _frameStride = 1;
- private double? _exposureTimeUs;
-
- public double? ExposureTimeUs
- {
- get => _exposureTimeUs;
- set => SetProperty(ref _exposureTimeUs, value);
- }
-
-
- /// 全局置信度阈值
- public float ConfidenceThreshold
- {
- get { return _confidenceThreshold; }
- set { SetProperty(ref _confidenceThreshold, value); }
- }
-
- /// 默认稳定帧数(条件未写 stable_frames 时用它)
- public int StableFrames
- {
- get { return _stableFrames; }
- set { SetProperty(ref _stableFrames, value); }
- }
-
- /// 区域命中容差(像素)
- public float PositionTolerance
- {
- get { return _positionTolerance; }
- set { SetProperty(ref _positionTolerance, value); }
- }
-
- /// 启用超时违规
- public bool EnableTimeoutDetection
- {
- get { return _enableTimeoutDetection; }
- set { SetProperty(ref _enableTimeoutDetection, value); }
- }
-
- /// 整轮完成后自动复位
- public bool AutoResetOnComplete
- {
- get { return _autoResetOnComplete; }
- set { SetProperty(ref _autoResetOnComplete, value); }
- }
-
- /// 复位前停留秒数
- public int ResetDelaySec
- {
- get { return _resetDelaySec; }
- set { SetProperty(ref _resetDelaySec, value); }
- }
-
- /// 抽帧间隔(1=每帧都判)
- public int FrameStride
- {
- get { return _frameStride; }
- set { SetProperty(ref _frameStride, value); }
- }
-
- /// 读入
- public void CopyFrom(SopSettings from)
- {
- ExposureTimeUs = from.ExposureTimeUs;
- ConfidenceThreshold = from.ConfidenceThreshold;
- StableFrames = from.StableFrames;
- PositionTolerance = from.PositionTolerance;
- EnableTimeoutDetection = from.EnableTimeoutDetection;
- AutoResetOnComplete = from.AutoResetOnComplete;
- ResetDelaySec = from.ResetDelaySec;
- FrameStride = from.FrameStride;
- }
-
- /// 写出
- public void CopyTo(SopSettings to)
- {
- to.ExposureTimeUs = ExposureTimeUs;
- to.ConfidenceThreshold = ConfidenceThreshold;
- to.StableFrames = StableFrames;
- to.PositionTolerance = PositionTolerance;
- to.EnableTimeoutDetection = EnableTimeoutDetection;
- to.AutoResetOnComplete = AutoResetOnComplete;
- to.ResetDelaySec = ResetDelaySec;
- to.FrameStride = FrameStride;
- }
-}
-
-///
-/// sop.model
-///
-public class RecipeModelNode : EditorNode
-{
- private string _path = "";
- private int _inputSize = 640;
-
- /// onnx 路径(相对程序目录)
- public string Path
- {
- get { return _path; }
- set { SetProperty(ref _path, value); }
- }
-
- /// 类别名(顺序必须与训练时一致)
- public EditableList Classes { get; } = new() { Title = "类别名(顺序须与训练一致)" };
-
- /// 输入尺寸
- public int InputSize
- {
- get { return _inputSize; }
- set { SetProperty(ref _inputSize, value); }
- }
-
- /// 读入
- public void CopyFrom(ModelDef from)
- {
- Path = from.Path;
- InputSize = from.InputSize;
-
- Classes.Items.Clear();
- foreach (var name in from.Classes) Classes.Items.Add(new TextItem { Text = name, RemoveCommand = Classes.RemoveCommand });
- }
-}
-
-///
-/// regions 里的一项(Key = 配方里引用的区域名,即 YAML 的字典键)
-///
-public class RegionNode : EditorNode
-{
- /// 整组更新,属性通知发出时四个坐标已一致。
- public void SetBounds(System.Windows.Int32Rect bounds)
- {
- _x1 = bounds.X; _y1 = bounds.Y; _x2 = bounds.X + bounds.Width; _y2 = bounds.Y + bounds.Height;
- RaisePropertyChanged(nameof(X1)); RaisePropertyChanged(nameof(Y1));
- RaisePropertyChanged(nameof(X2)); RaisePropertyChanged(nameof(Y2));
- }
-
- private string _key = "";
- private int _x1;
- private int _y1;
- private int _x2;
- private int _y2;
- private string _name = "";
- private string _description = "";
- private string _color = "#4CAF50";
-
- /// 区域键名(YAML 的键,条件里引用的就是它)
- public string Key
- {
- get { return _key; }
- set
- {
- var old = _key;
- if (!SetProperty(ref _key, value)) return;
- if (!string.IsNullOrWhiteSpace(old)) Renamed?.Invoke(old, value);
- }
- }
-
- /// 左上 X
- public int X1
- {
- get { return _x1; }
- set { SetProperty(ref _x1, value); }
- }
-
- /// 左上 Y
- public int Y1
- {
- get { return _y1; }
- set { SetProperty(ref _y1, value); }
- }
-
- /// 右下 X
- public int X2
- {
- get { return _x2; }
- set { SetProperty(ref _x2, value); }
- }
-
- /// 右下 Y
- public int Y2
- {
- get { return _y2; }
- set { SetProperty(ref _y2, value); }
- }
-
- /// 显示名
- public string Name
- {
- get { return _name; }
- set { SetProperty(ref _name, value); }
- }
-
- /// 说明
- public string Description
- {
- get { return _description; }
- set { SetProperty(ref _description, value); }
- }
-
- /// 显示颜色(#RRGGBB)
- public string Color
- {
- get { return _color; }
- set
- {
- if (!SetProperty(ref _color, value)) return;
- RaisePropertyChanged(nameof(Brush));
- }
- }
-
- /// 色块预览(解析失败退回默认绿,别炸界面)
- public SolidColorBrush Brush
- {
- get
- {
- try
- {
- return new SolidColorBrush((System.Windows.Media.Color)ColorConverter.ConvertFromString(Color));
- }
- catch
- {
- return new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x4C, 0xAF, 0x50));
- }
- }
- }
-
- /// 区域键名变了(配方里的引用要跟着改)
- public event Action? Renamed;
-
- /// 读入
- public void CopyFrom(RegionDef from)
- {
- X1 = from.X1;
- Y1 = from.Y1;
- X2 = from.X2;
- Y2 = from.Y2;
- Name = from.Name;
- Description = from.Description;
- Color = from.Color;
- }
-
- /// 写出
- public void CopyTo(RegionDef to)
- {
- to.X1 = X1;
- to.Y1 = Y1;
- to.X2 = X2;
- to.Y2 = Y2;
- to.Name = Name;
- to.Description = Description;
- to.Color = Color;
- }
-}
-
-///
-/// steps 里的一项
-///
-public class StepNode : EditorNode
-{
- private int _id;
- private string _name = "";
- private string _description = "";
- private int _timeout;
- private int _standardDurationMs;
- // 即使 YAML 没有 detection,也保留可编辑对象,供界面写入新选择的方法。
- private ConditionNode? _detection = new();
-
- /// 步骤号(执行顺序按它升序)
- public int Id
- {
- get { return _id; }
- set { SetProperty(ref _id, value); }
- }
-
- /// 步骤名
- public string Name
- {
- get { return _name; }
- set { SetProperty(ref _name, value); }
- }
-
- /// 说明
- public string Description
- {
- get { return _description; }
- set { SetProperty(ref _description, value); }
- }
-
- /// 本步超时秒数(0=不限制)
- public int Timeout
- {
- get { return _timeout; }
- set { SetProperty(ref _timeout, value); }
- }
-
- /// 标准节拍毫秒(报表用,不参与判定)
- public int StandardDurationMs
- {
- get { return _standardDurationMs; }
- set { SetProperty(ref _standardDurationMs, value); }
- }
-
- /// 判定条件(method 留空 = 本步不写 detection 节点)
- public ConditionNode? Detection
- {
- get { return _detection; }
- set { SetProperty(ref _detection, value); }
- }
-
- /// 本步期间必须常在的物体
- public EditableList MustKeep { get; } = new() { Title = "本步期间必须在的物体(被拿走即违规)" };
-
- /// 本步完成时必须存在的物体
- public EditableList RequiredObjects { get; } = new() { Title = "本步完成时必须存在的物体(漏放/缺料)" };
-
- /// 违规规则
- public EditableList ViolationRules { get; } = new() { Title = "违规规则" };
-
- /// 本步是否有判定条件(取消勾选就清掉条件)
- public bool HasCondition
- {
- get { return Detection is not null; }
- set
- {
- if (value) Detection ??= new ConditionNode();
- else Detection = null;
-
- RaisePropertyChanged();
- }
- }
-}
-
-///
-/// 步骤的判定条件
-///
-public class ConditionNode : EditorNode
-{
- private string _method = "";
- private string _targetObject = "";
- private string _region = "";
- private string _fromRegion = "";
- private string _toRegion = "";
- private string _hand = "any";
- private float _tolerance = 60f;
- private float _minConfidence = 0.7f;
- private int _stableFrames = 5;
- private int _durationMs;
-
- /// 判定方法
- public string Method
- {
- get { return _method; }
- set { SetProperty(ref _method, value); }
- }
-
- /// 目标物体类别
- public string TargetObject
- {
- get { return _targetObject; }
- set { SetProperty(ref _targetObject, value); }
- }
-
- /// 主区域名
- public string Region
- {
- get { return _region; }
- set { SetProperty(ref _region, value); }
- }
-
- /// 起点区域名(hand_move 的 from)
- public string FromRegion
- {
- get { return _fromRegion; }
- set { SetProperty(ref _fromRegion, value); }
- }
-
- /// 终点区域名(hand_move 的 to)
- public string ToRegion
- {
- get { return _toRegion; }
- set { SetProperty(ref _toRegion, value); }
- }
-
- /// 手:any/left/right
- public string Hand
- {
- get { return _hand; }
- set { SetProperty(ref _hand, value); }
- }
-
- /// 手-物相邻容差(像素)
- public float Tolerance
- {
- get { return _tolerance; }
- set { SetProperty(ref _tolerance, value); }
- }
-
- /// 本条件置信度阈值
- public float MinConfidence
- {
- get { return _minConfidence; }
- set { SetProperty(ref _minConfidence, value); }
- }
-
- /// 稳定帧数
- public int StableFrames
- {
- get { return _stableFrames; }
- set { SetProperty(ref _stableFrames, value); }
- }
-
- /// 计时毫秒(time_elapsed 用)
- public int DurationMs
- {
- get { return _durationMs; }
- set { SetProperty(ref _durationMs, value); }
- }
-
- /// 读入
- public static ConditionNode From(StepCondition from) => new()
- {
- Method = from.Method,
- TargetObject = from.TargetObject,
- Region = from.Region,
- FromRegion = from.FromRegion,
- ToRegion = from.ToRegion,
- Hand = from.Hand,
- Tolerance = from.Tolerance,
- MinConfidence = from.MinConfidence,
- StableFrames = from.StableFrames,
- DurationMs = from.DurationMs,
- };
-
- /// 写出
- public StepCondition ToCondition() => new()
- {
- Method = Method,
- TargetObject = TargetObject,
- Region = Region,
- FromRegion = FromRegion,
- ToRegion = ToRegion,
- Hand = Hand,
- Tolerance = Tolerance,
- MinConfidence = MinConfidence,
- StableFrames = StableFrames,
- DurationMs = DurationMs,
- };
-}
-
-///
-/// 违规规则
-///
-public class ViolationRuleNode : EditorNode, IRemovable
-{
- private string _type = ViolationType.Timeout;
- private string _description = "";
- private int _severity = 1;
-
- /// 违规类型
- public string Type
- {
- get { return _type; }
- set { SetProperty(ref _type, value); }
- }
-
- /// 描述(告警横幅文案)
- public string Description
- {
- get { return _description; }
- set { SetProperty(ref _description, value); }
- }
-
- /// 严重度
- public int Severity
- {
- get { return _severity; }
- set { SetProperty(ref _severity, value); }
- }
-
- ///
- public ICommand? RemoveCommand { get; set; }
-
- /// 读入
- public static ViolationRuleNode From(ViolationRule from, ICommand? removeCommand = null) => new()
- {
- Type = from.Type,
- Description = from.Description,
- Severity = from.Severity,
- RemoveCommand = removeCommand,
- };
-
- /// 写出
- public ViolationRule ToRule() => new()
- {
- Type = Type,
- Description = Description,
- Severity = Severity,
- };
-}
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml
deleted file mode 100644
index 3524528..0000000
--- a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml
+++ /dev/null
@@ -1,607 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml.cs b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml.cs
deleted file mode 100644
index 28df77d..0000000
--- a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace SopHelper.VVMs.RecipeEditor;
-
-///
-/// 配方编辑器(弹窗)。ViewModel 按命名约定自动绑定,见 App.ConfigureViewModelLocator。
-///
-public partial class RecipeEditor : System.Windows.Controls.UserControl
-{
- ///
- /// 配方编辑器
- ///
- public RecipeEditor()
- {
- InitializeComponent();
- }
-}
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs
deleted file mode 100644
index f7b8043..0000000
--- a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs
+++ /dev/null
@@ -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;
-
-///
-/// 配方编辑器(SOP 页「编辑」按钮弹出)。表单在 EditorNodes 那一侧,
-/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
-/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
-///
-public class RecipeEditorViewModel : BindableBase, IDialogAware
-{
- private RecipeNode _recipe = new();
- private string _path = "";
- private bool _isNew;
- private Action? _onSaved;
- private readonly HashSet _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; }
-
- /// 当前编辑的配方目录(configs/sop)
- private string _directory = "";
-
- ///
- public string Title => _isNew ? "新建配方" : $"编辑配方 - {FileNameText}";
-
- ///
- public DialogCloseListener RequestClose { get; } = new();
-
- /// 标题栏显示的文件名
- public string FileNameText => string.IsNullOrEmpty(_path) ? $"{_recipe.FileName}.yaml(新建)" : Path.GetFileName(_path);
-
- /// 编辑中的配方
- public RecipeNode Recipe
- {
- get { return _recipe; }
- private set
- {
- if (!SetProperty(ref _recipe, value)) return;
- RaisePropertyChanged(nameof(FileNameText));
- RaisePropertyChanged(nameof(Title));
- }
- }
-
- /// 保存前的校验提醒(不阻止保存——现场常见"先存草稿再补区域")
- public ObservableCollection Warnings { get; } = [];
-
- /// 保存
- public DelegateCommand SaveCommand { get; private set; } = null!;
-
- /// 关闭编辑器,未保存的修改不写入文件
- public DelegateCommand CloseCommand { get; private set; } = null!;
-
- ///
- /// 配方编辑器
- ///
- 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);
- }
-
- ///
- public void OnDialogOpened(IDialogParameters parameters)
- {
- _directory = parameters.GetValue("directory") ?? "";
- _path = parameters.GetValue("path") ?? "";
- _isNew = parameters.GetValue("new");
- _onSaved = parameters.GetValue>("onSaved");
- SaveStatus = "";
- _camera = parameters.GetValue("cameraService");
- _cameraInfo = parameters.GetValue("cameraInfo");
- PreviewImage = parameters.GetValue("preview");
- CaptureImageCommand.RaiseCanExecuteChanged();
- if (PreviewImage is not null) DescribeImage("最近一帧");
- else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
-
- var config = parameters.GetValue("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();
- }
-
- ///
- public bool CanCloseDialog() => !IsCapturing;
-
- ///
- 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(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);
- }
- }
-
- ///
- /// 用当前编辑结果跑一遍加载器校验(就是"这一步永远不推进"那类问题)
- ///
- private void RefreshWarnings()
- {
- SaveStatus = "";
- // 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。
- var current = new HashSet(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();
-}
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs b/src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs
deleted file mode 100644
index c675236..0000000
--- a/src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs
+++ /dev/null
@@ -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;
-
-/// 图像按比例居中显示;拖动坐标映射到原图像素,留白不参与标定。
-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), 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? Regions { get => (ObservableCollection?)GetValue(RegionsProperty); set => SetValue(RegionsProperty, value); }
- public RegionNode? SelectedRegion { get => (RegionNode?)GetValue(SelectedRegionProperty); set => SetValue(SelectedRegionProperty, value); }
-
- private readonly HashSet _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 old) old.CollectionChanged -= canvas.CollectionChanged;
- if (e.NewValue is ObservableCollection 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();
-}
diff --git a/src/SopHelper.App/VVMs/SopPage/DetectionOverlay.cs b/src/SopHelper.App/VVMs/SopPage/DetectionOverlay.cs
deleted file mode 100644
index d296b09..0000000
--- a/src/SopHelper.App/VVMs/SopPage/DetectionOverlay.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-using System.Globalization;
-using System.Windows;
-using System.Windows.Media;
-using SopHelper.Engine.Common;
-
-namespace SopHelper.VVMs.SopPage;
-
-/// 按原图像素绘制目标框与标签,与视频一起缩放。
-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();
- }
-}
diff --git a/src/SopHelper.App/VVMs/SopPage/HandOverlay.cs b/src/SopHelper.App/VVMs/SopPage/HandOverlay.cs
deleted file mode 100644
index 89621d1..0000000
--- a/src/SopHelper.App/VVMs/SopPage/HandOverlay.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-using System.Windows;
-using System.Windows.Media;
-using SopHelper.Engine.Common;
-
-namespace SopHelper.VVMs.SopPage;
-
-/// 按原图坐标绘制手部结果,与视频、ROI 一起缩放,不修改用于检测的图像。
-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();
- }
-}
diff --git a/src/SopHelper.App/VVMs/SopPage/SopPage.xaml b/src/SopHelper.App/VVMs/SopPage/SopPage.xaml
deleted file mode 100644
index 83a34b1..0000000
--- a/src/SopHelper.App/VVMs/SopPage/SopPage.xaml
+++ /dev/null
@@ -1,282 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.App/VVMs/SopPage/SopPage.xaml.cs b/src/SopHelper.App/VVMs/SopPage/SopPage.xaml.cs
deleted file mode 100644
index 053b06b..0000000
--- a/src/SopHelper.App/VVMs/SopPage/SopPage.xaml.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-using SopHelper.Core.Prism;
-
-namespace SopHelper.VVMs.SopPage;
-
-///
-/// SOP 主页(画面 + 步骤卡 + 参数)
-///
-[NavigationPage(ViewName = "SopPage", DisplayName = "SOP 辅助", Index = 0)]
-public partial class SopPage : System.Windows.Controls.UserControl
-{
- ///
- /// SOP 主页
- ///
- public SopPage()
- {
- InitializeComponent();
- }
-}
diff --git a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs
deleted file mode 100644
index f2e4370..0000000
--- a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs
+++ /dev/null
@@ -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;
-
-///
-/// SOP 主页视图模型:相机 → 推理管线 → SOP 引擎,界面只订阅事件。
-///
-public class SopPageViewModel : ViewModelBase
-{
- private const int MaxLogLines = 300;
- private const int MaxTopViolations = 3;
-
- /// 配方目录(相对程序目录)
- 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");
-
- /// 配方编辑器弹窗的注册名(见 App.RegisterTypes)
- 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;
-
- /// 采集线程写、UI 线程取最新帧
- private readonly object _frameLock = new();
-
- private Mat? _pending;
- private bool _destroyed;
-
- /// 最近一次处理过的帧(快照按钮存盘用,由推理线程写入)
- 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;
-
- ///
- /// SOP 主页视图模型
- ///
- 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();
- }
-
- /// 可用相机
- public ObservableCollection Cameras { get; } = [];
-
- /// 可用配方文件
- public ObservableCollection Recipes { get; } = [];
-
- /// 步骤卡
- public ObservableCollection StepCards { get; } = [];
-
- /// Top3 违规
- public ObservableCollection Violations { get; } = [];
-
- /// 日志
- public ObservableCollection Logs { get; } = [];
-
- /// 画面 ROI
- public ObservableCollection Rois { get; } = [];
-
- /// 选中相机
- public CameraInfo? SelectedCamera
- {
- get { return _selectedCamera; }
- set
- {
- if (!SetProperty(ref _selectedCamera, value)) return;
- RaiseCommands(); // 实测:不刷新会导致"开始/停止"一直灰着,选了相机也点不动
- }
- }
-
- /// 选中配方
- public string? SelectedRecipe
- {
- get { return _selectedRecipe; }
- set
- {
- if (!SetProperty(ref _selectedRecipe, value)) return;
- RaiseCommands();
- }
- }
-
- /// 画面
- public ImageSource? Frame
- {
- get { return _frame; }
- set { SetProperty(ref _frame, value); }
- }
-
- /// 最近一次推理结果,供图像上的手部与目标检测绘制层使用。
- public FrameResult? HandResult
- {
- get => _handResult;
- private set => SetProperty(ref _handResult, value);
- }
-
- /// 状态
- public string StatusText
- {
- get { return _statusText; }
- set { SetProperty(ref _statusText, value); }
- }
-
- /// 结果帧率
- public string FpsText
- {
- get { return _fpsText; }
- set { SetProperty(ref _fpsText, value); }
- }
-
- /// 推理耗时
- public string InferenceText
- {
- get { return _inferenceText; }
- set { SetProperty(ref _inferenceText, value); }
- }
-
- /// 是否运行中
- public bool IsRunning
- {
- get { return _isRunning; }
- set
- {
- if (!SetProperty(ref _isRunning, value)) return;
- if (!value) HandResult = null;
- RaisePropertyChanged(nameof(CanSelectCamera));
- RaiseCommands();
- }
- }
-
- /// 连接、枚举、采集期间不切换设备。
- public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
-
- /// 相机是否已连接
- public bool IsConnected
- {
- get { return _isConnected; }
- set
- {
- if (!SetProperty(ref _isConnected, value)) return;
- RaisePropertyChanged(nameof(ConnectionText));
- }
- }
-
- /// 右下角连接文字(实测静态文字不反映状态,改成绑定)
- public string ConnectionText => IsConnected ? "相机已连接" : "相机未连接";
-
- /// 画面像素宽(ROI 覆盖层按它缩放)
- public double FrameWidth
- {
- get { return _frameWidth; }
- set { SetProperty(ref _frameWidth, value); }
- }
-
- /// 画面像素高
- public double FrameHeight
- {
- get { return _frameHeight; }
- set { SetProperty(ref _frameHeight, value); }
- }
-
- /// 置信度阈值(透传给 YOLO)
- public double Confidence
- {
- get { return _confidence; }
- set { SetProperty(ref _confidence, value); }
- }
-
- /// 抽帧间隔
- public int FrameStride
- {
- get { return _frameStride; }
- set { SetProperty(ref _frameStride, value); }
- }
-
- /// 刷新相机列表
- public DelegateCommand RefreshCamerasCommand { get; private set; } = null!;
-
- /// 开始 / 停止
- public DelegateCommand StartStopCommand { get; private set; } = null!;
-
- /// 暂停 / 继续
- public DelegateCommand TogglePauseCommand { get; private set; } = null!;
-
- /// 复位
- public DelegateCommand ResetCommand { get; private set; } = null!;
-
- /// 应用配方
- public DelegateCommand ApplyRecipeCommand { get; private set; } = null!;
-
- /// 快照
- public DelegateCommand SnapshotCommand { get; private set; } = null!;
-
- /// 编辑当前选中的配方(弹窗)
- public DelegateCommand EditRecipeCommand { get; private set; } = null!;
-
- /// 新建配方(弹窗)
- 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();
- }
-
- /// 运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用
- private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
-
- ///
- /// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
- /// 绑定上去的按钮不会因属性变化自动亮起来(实测:选了相机"开始/停止"仍灰着)。
- ///
- private void RaiseCommands()
- {
- // 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
- RefreshCamerasCommand?.RaiseCanExecuteChanged();
- StartStopCommand?.RaiseCanExecuteChanged();
- TogglePauseCommand?.RaiseCanExecuteChanged();
- ResetCommand?.RaiseCanExecuteChanged();
- ApplyRecipeCommand?.RaiseCanExecuteChanged();
- SnapshotCommand?.RaiseCanExecuteChanged();
- EditRecipeCommand?.RaiseCanExecuteChanged();
- NewRecipeCommand?.RaiseCanExecuteChanged();
- }
-
- ///
- /// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期
- ///
- private void OnCameraFrame(CameraFrame frame)
- {
- lock (_frameLock)
- {
- if (_destroyed) return;
- var clone = frame.Bgr.Clone();
- var old = _pending;
- _pending = clone;
- old?.Dispose();
- }
- }
-
- ///
- /// 快照:把最近处理过的帧连同 ROI 存到 snaps/
- ///
- 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}");
- }
- }
-
- ///
- public override void Destroy()
- {
- _renderTimer.Stop();
- _camera.FrameArrived -= OnCameraFrame;
-
- lock (_frameLock)
- {
- _destroyed = true;
- _pending?.Dispose();
- _pending = null;
- }
-
- // 相机与推理管线是应用级单例,由 App.OnExit 按顺序统一释放。
-
- base.Destroy();
- }
-
- ///
- /// 扫描 configs/sop/*.yaml
- ///
- 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];
- }
-
- ///
- /// 编辑器保存后:重扫目录(新建的文件要能选到),选中刚存的那个,再重新应用一次
- ///
- 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();
- }
-
- ///
- /// 编辑当前选中的配方
- ///
- private void EditRecipe()
- {
- var path = Path.Combine(RecipeDirectory, SelectedRecipe!);
- if (!File.Exists(path))
- {
- Log("warn", $"配方不存在:{path}");
- return;
- }
-
- // 编辑器读的是这个已解析的 config(含校验提醒),保存时再整体映射回去
- OpenEditor(path, false, SopConfigLoader.Load(path));
- }
-
- ///
- /// 新建配方(空白配方,文件名在编辑器里填)
- ///
- private void NewRecipe()
- {
- OpenEditor("", true, new SopConfig());
- }
-
- ///
- /// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
- ///
- 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(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(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 文件");
- }
-
- ///
- /// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
- ///
- 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";
- }
-
- ///
- /// 渲染定时器:取采集线程留下的最新帧
- ///
- 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 });
- }
-}
-
-///
-/// 步骤卡数据
-///
-public class StepCard : ViewModelBase
-{
- private bool _isCurrent;
- private bool _isMet;
- private string _message = "";
-
- /// 步骤 Id
- public int StepId { get; set; }
-
- /// 步骤名
- public string Name { get; set; } = "";
-
- /// 当前步骤
- public bool IsCurrent
- {
- get { return _isCurrent; }
- set { SetProperty(ref _isCurrent, value); }
- }
-
- /// 已完成
- public bool IsMet
- {
- get { return _isMet; }
- set { SetProperty(ref _isMet, value); }
- }
-
- /// 判定说明
- public string Message
- {
- get { return _message; }
- set { SetProperty(ref _message, value); }
- }
-}
-
-///
-/// Top3 违规条目
-///
-public class ViolationItem
-{
- /// 时刻
- public DateTime Time { get; set; }
-
- /// 步骤 Id
- public int StepId { get; set; }
-
- /// 类型
- public string Type { get; set; } = "";
-
- /// 文案
- public string Message { get; set; } = "";
-}
-
-///
-/// 日志条目
-///
-public class LogItem
-{
- /// 时刻
- public DateTime Time { get; set; }
-
- /// 级别 info/warn/viol
- public string Level { get; set; } = "info";
-
- /// 文案
- public string Message { get; set; } = "";
-}
-
-///
-/// ROI 覆盖层条目(坐标 = 配方像素坐标,外层 Viewbox 负责缩放)
-///
-public class RoiItem
-{
- /// 区域名
- public string Name { get; set; } = "";
-
- /// X
- public double X { get; set; }
-
- /// Y
- public double Y { get; set; }
-
- /// W
- public double W { get; set; }
-
- /// H
- public double H { get; set; }
-
- /// 颜色(#RRGGBB)。不叫 Color——会和 System.Windows.Media.Color 撞名
- public string ColorHex { get; set; } = "#4CAF50";
-
- /// 画刷
- public SolidColorBrush Brush => new((System.Windows.Media.Color)ColorConverter.ConvertFromString(ColorHex));
-}
diff --git a/src/SopHelper.App/Assets/bws.svg b/src/SopHelper.Avalonia/Assets/bws.svg
similarity index 100%
rename from src/SopHelper.App/Assets/bws.svg
rename to src/SopHelper.Avalonia/Assets/bws.svg
diff --git a/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj b/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
index bf0d917..07be691 100644
--- a/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
+++ b/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
@@ -15,12 +15,12 @@
Linux
-
+
-
+
diff --git a/src/SopHelper.Avalonia/Training/MainViewModel.cs b/src/SopHelper.Avalonia/Training/MainViewModel.cs
index 269e62c..f4d8197 100644
--- a/src/SopHelper.Avalonia/Training/MainViewModel.cs
+++ b/src/SopHelper.Avalonia/Training/MainViewModel.cs
@@ -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 () =>
diff --git a/src/SopHelper.Engine/Camera/CameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/CameraService.cs
similarity index 100%
rename from src/SopHelper.Engine/Camera/CameraService.cs
rename to src/SopHelper.CrossPlatform.Engine/Camera/CameraService.cs
diff --git a/src/SopHelper.Engine/Camera/HikvisionCameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/HikvisionCameraService.cs
similarity index 100%
rename from src/SopHelper.Engine/Camera/HikvisionCameraService.cs
rename to src/SopHelper.CrossPlatform.Engine/Camera/HikvisionCameraService.cs
diff --git a/src/SopHelper.Engine/Camera/ICameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/ICameraService.cs
similarity index 100%
rename from src/SopHelper.Engine/Camera/ICameraService.cs
rename to src/SopHelper.CrossPlatform.Engine/Camera/ICameraService.cs
diff --git a/src/SopHelper.CrossPlatform.Engine/UvcCameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs
similarity index 100%
rename from src/SopHelper.CrossPlatform.Engine/UvcCameraService.cs
rename to src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs
diff --git a/src/SopHelper.Engine/Camera/VideoRecorder.cs b/src/SopHelper.CrossPlatform.Engine/Camera/VideoRecorder.cs
similarity index 100%
rename from src/SopHelper.Engine/Camera/VideoRecorder.cs
rename to src/SopHelper.CrossPlatform.Engine/Camera/VideoRecorder.cs
diff --git a/src/SopHelper.Engine/Common/Types.cs b/src/SopHelper.CrossPlatform.Engine/Common/Types.cs
similarity index 100%
rename from src/SopHelper.Engine/Common/Types.cs
rename to src/SopHelper.CrossPlatform.Engine/Common/Types.cs
diff --git a/src/SopHelper.Engine/Inference/CpuSessionTuning.cs b/src/SopHelper.CrossPlatform.Engine/Inference/CpuSessionTuning.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/CpuSessionTuning.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/CpuSessionTuning.cs
diff --git a/src/SopHelper.Engine/Inference/CudaRuntime.cs b/src/SopHelper.CrossPlatform.Engine/Inference/CudaRuntime.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/CudaRuntime.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/CudaRuntime.cs
diff --git a/src/SopHelper.Engine/Inference/HandednessDecoder.cs b/src/SopHelper.CrossPlatform.Engine/Inference/HandednessDecoder.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/HandednessDecoder.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/HandednessDecoder.cs
diff --git a/src/SopHelper.Engine/Inference/HandednessStabilizer.cs b/src/SopHelper.CrossPlatform.Engine/Inference/HandednessStabilizer.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/HandednessStabilizer.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/HandednessStabilizer.cs
diff --git a/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs b/src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/MediaPipeHandDetector.cs
diff --git a/src/SopHelper.Engine/Inference/PalmModelLoader.cs b/src/SopHelper.CrossPlatform.Engine/Inference/PalmModelLoader.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/PalmModelLoader.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/PalmModelLoader.cs
diff --git a/src/SopHelper.Engine/Inference/YoloDetector.cs b/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs
similarity index 100%
rename from src/SopHelper.Engine/Inference/YoloDetector.cs
rename to src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs
diff --git a/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
similarity index 100%
rename from src/SopHelper.Engine/Pipeline/DetectionPipeline.cs
rename to src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
diff --git a/src/SopHelper.Engine/Sop/ConditionEvaluator.cs b/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
similarity index 100%
rename from src/SopHelper.Engine/Sop/ConditionEvaluator.cs
rename to src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
diff --git a/src/SopHelper.Engine/Sop/SopConfig.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
similarity index 100%
rename from src/SopHelper.Engine/Sop/SopConfig.cs
rename to src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
diff --git a/src/SopHelper.Engine/Sop/SopConfigLoader.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
similarity index 100%
rename from src/SopHelper.Engine/Sop/SopConfigLoader.cs
rename to src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
diff --git a/src/SopHelper.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
similarity index 100%
rename from src/SopHelper.Engine/Sop/SopEngine.cs
rename to src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
diff --git a/src/SopHelper.Engine/Sop/ViolationDetector.cs b/src/SopHelper.CrossPlatform.Engine/Sop/ViolationDetector.cs
similarity index 100%
rename from src/SopHelper.Engine/Sop/ViolationDetector.cs
rename to src/SopHelper.CrossPlatform.Engine/Sop/ViolationDetector.cs
diff --git a/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj b/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj
index cbf46fd..d5e0bd5 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj
+++ b/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj
@@ -4,7 +4,6 @@
enable
enable
true
- false
Linux
Windows
Windows
@@ -13,8 +12,6 @@
../../libs/MvCameraControl.Net.dll
-
-
$(MvsManagedSdk)true
diff --git a/src/SopHelper.Engine/Training/Project.cs b/src/SopHelper.CrossPlatform.Engine/Training/Project.cs
similarity index 100%
rename from src/SopHelper.Engine/Training/Project.cs
rename to src/SopHelper.CrossPlatform.Engine/Training/Project.cs
diff --git a/src/SopHelper.Engine/Training/WorkerClient.cs b/src/SopHelper.CrossPlatform.Engine/Training/WorkerClient.cs
similarity index 100%
rename from src/SopHelper.Engine/Training/WorkerClient.cs
rename to src/SopHelper.CrossPlatform.Engine/Training/WorkerClient.cs
diff --git a/src/SopHelper.Engine/Camera/UvcCameraService.cs b/src/SopHelper.Engine/Camera/UvcCameraService.cs
deleted file mode 100644
index fda84cd..0000000
--- a/src/SopHelper.Engine/Camera/UvcCameraService.cs
+++ /dev/null
@@ -1,288 +0,0 @@
-using OpenCvSharp;
-
-namespace SopHelper.Engine.Camera;
-
-///
-/// USB(UVC)相机实现。单相机最小版。
-/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
-///
-public class UvcCameraService : ICameraService
-{
- ///
- /// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
- /// 旧图还在异步销毁时开新图会触发 AccessViolationException。
- ///
- private static readonly object DshowLock = new();
-
- private readonly object _captureLock = new();
- private VideoCapture? _capture;
- private CancellationTokenSource? _cts;
- private Task? _grabTask;
- private long _frameId;
-
- ///
- public bool IsConnected { get; private set; }
-
- ///
- public bool IsGrabbing { get; private set; }
-
- ///
- public event Action? FrameArrived;
-
- ///
- public event Action? ConnectionChanged;
-
- ///
- public event Action? Error;
-
- /// 当前相机
- public CameraInfo? Current { get; private set; }
-
- /// 实测帧率(每 2 秒刷新一次)
- public double ActualFps { get; private set; }
-
- ///
- public Task> EnumerateAsync()
- {
- return Task.Run(() =>
- {
- var list = new List();
-
- 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;
- });
- }
-
- ///
- public Task 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;
- });
- }
-
- ///
- public Task 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;
- });
- }
-
- ///
- /// 采集循环
- ///
- 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;
-
- ///
- public void Stop()
- {
- _cts?.Cancel();
-
- try
- {
- _grabTask?.Wait(TimeSpan.FromSeconds(2));
- }
- catch
- {
- // 取消异常忽略
- }
-
- _grabTask = null;
- _cts?.Dispose();
- _cts = null;
- IsGrabbing = false;
- }
-
- ///
- 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);
- }
-
- ///
- public void Dispose()
- {
- Disconnect();
- }
-
- ///
- /// 用指定后端尝试打开
- ///
- 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;
- }
- }
-}
diff --git a/src/SopHelper.Engine/SopHelper.Engine.csproj b/src/SopHelper.Engine/SopHelper.Engine.csproj
deleted file mode 100644
index 4a762fb..0000000
--- a/src/SopHelper.Engine/SopHelper.Engine.csproj
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
- net8.0
- latest
- enable
- enable
- x64
- AnyCPU;x64
- true
- SopHelper.Engine
- SopHelper.Engine
-
-
-
-
- ..\..\libs\MvCameraControl.Net.dll
- true
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.Linux.Engine/SopHelper.Linux.Engine.csproj b/src/SopHelper.Linux.Engine/SopHelper.Linux.Engine.csproj
deleted file mode 100644
index 1fc813f..0000000
--- a/src/SopHelper.Linux.Engine/SopHelper.Linux.Engine.csproj
+++ /dev/null
@@ -1,21 +0,0 @@
-
-
- net8.0
- enable
- enable
- true
- false
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.Linux/DetectionSession.cs b/src/SopHelper.Linux/DetectionSession.cs
deleted file mode 100644
index b0e67a5..0000000
--- a/src/SopHelper.Linux/DetectionSession.cs
+++ /dev/null
@@ -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 _commands = new();
- private readonly object _frameGate = new();
- private Mat? _lastFrame;
- public event Action? Preview;
- public event Action? Step;
- public event Action? Log;
- public event Action? 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; } }
-}
diff --git a/src/SopHelper.Linux/MainWindow.cs b/src/SopHelper.Linux/MainWindow.cs
deleted file mode 100644
index 2d2c3ba..0000000
--- a/src/SopHelper.Linux/MainWindow.cs
+++ /dev/null
@@ -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 _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 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(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);
-}
diff --git a/src/SopHelper.Linux/Program.cs b/src/SopHelper.Linux/Program.cs
deleted file mode 100644
index 350592c..0000000
--- a/src/SopHelper.Linux/Program.cs
+++ /dev/null
@@ -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().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(); 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; }
- }
-}
diff --git a/src/SopHelper.Linux/SopHelper.Linux.csproj b/src/SopHelper.Linux/SopHelper.Linux.csproj
deleted file mode 100644
index 568e0fc..0000000
--- a/src/SopHelper.Linux/SopHelper.Linux.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
- Exe
- net8.0
- enable
- enable
- true
- SopHelper.Linux
-
-
-
-
-
-
-
-
-
diff --git a/tests/HandDetectionSmoke/HandDetectionSmoke.csproj b/tests/HandDetectionSmoke/HandDetectionSmoke.csproj
index a9ad8ab..e32ed63 100644
--- a/tests/HandDetectionSmoke/HandDetectionSmoke.csproj
+++ b/tests/HandDetectionSmoke/HandDetectionSmoke.csproj
@@ -7,6 +7,6 @@
x64
-
+
diff --git a/tests/HandednessSmoke/HandednessSmoke.csproj b/tests/HandednessSmoke/HandednessSmoke.csproj
index 6a46a46..e882111 100644
--- a/tests/HandednessSmoke/HandednessSmoke.csproj
+++ b/tests/HandednessSmoke/HandednessSmoke.csproj
@@ -6,8 +6,8 @@
enable
-
-
-
+
+
+
diff --git a/tests/RegionEditorSmoke/Program.cs b/tests/RegionEditorSmoke/Program.cs
deleted file mode 100644
index 5603313..0000000
--- a/tests/RegionEditorSmoke/Program.cs
+++ /dev/null
@@ -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();
- var saveVm = new RecipeEditorViewModel();
- try
- {
- saveVm.OnDialogOpened(new DialogParameters
- {
- { "directory", saveDirectory }, { "new", true },
- { "onSaved", new Action(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().Single();
- editorTabs.SelectedItem = editorTabs.Items.OfType().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