FocusAnalyzerViewModel.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. using Cognex.VisionPro;
  2. using OpenCvSharp;
  3. using OpenCvSharp.WpfExtensions;
  4. using OxyPlot;
  5. using OxyPlot.Axes;
  6. using OxyPlot.Series;
  7. using Prism.Commands;
  8. using Prism.Events;
  9. using Prism.Ioc;
  10. using Prism.Mvvm;
  11. using Prism.Regions;
  12. using SqlSugar;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Collections.ObjectModel;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using System.Windows.Forms;
  20. using System.Windows.Input;
  21. using System.Windows.Media;
  22. using System.Windows.Media.Imaging;
  23. using System.Windows.Threading;
  24. using TeamAAS_VP.Core;
  25. using TeamAAS_VP.Core.Lights;
  26. using TeamAAS_VP.Enums;
  27. using TeamAAS_VP.Events;
  28. using TeamAAS_VP.Interfaces;
  29. using TeamAAS_VP.Models;
  30. using TeamAAS_VP.Resources.Languages;
  31. using TeamAAS_VP.Services;
  32. using static TeamAAS_VP.ViewModels.DebugMod.LightManualViewModel;
  33. namespace TeamAAS_VP.ViewModels.DebugMod
  34. {
  35. /// <summary>
  36. /// 用于棋盘格清晰度分析的 ViewModel。
  37. /// 提供图像加载、棋盘格检测、清晰度分析、ROI 管理、结果导出及趋势绘制等功能。
  38. /// 绑定到对应的用户控件,负责对 UI 的数据和命令交互。
  39. /// </summary>
  40. public class FocusAnalyzerViewModel : BindableBase, INavigationAware
  41. {
  42. // 事件聚合器、配置服务、相机服务的引用(由容器注入)
  43. IEventAggregator _eventAggregator;
  44. IConfigService _configService;
  45. ICameraService _cameraService;
  46. // 辅助服务(对话框、图像分析、棋盘检测)和定时器
  47. private readonly FileDialogService _fileDialogService;
  48. private readonly ImageAnalysisService _imageAnalysisService;
  49. private readonly CheckerboardDetectionService _checkerboardService;
  50. private readonly DispatcherTimer _analysisTimer;
  51. // 当前加载的 OpenCV Mat(需要及时释放)
  52. private Mat _currentMat;
  53. // 分析结果历史记录(用于导出与绘图)
  54. private List<AnalysisResult> _resultHistory;
  55. #region 属性
  56. /// <summary>
  57. /// 将 View 中的 ROI(画布坐标)转换为图像像素坐标的函数。
  58. /// View 侧需要设置此委托以便 ViewModel 能够将 ROI 转换为 OpenCvSharp.Rect。
  59. /// 返回 null 表示无法转换或 ROI 无效。
  60. /// </summary>
  61. public Func<RoiModel, OpenCvSharp.Rect?> RoiToImageRectConverter { get; set; }
  62. private string _title = Lang.棋盘格清晰度分析工具;
  63. /// <summary>
  64. /// 窗口或控件标题(用于显示)。
  65. /// </summary>
  66. public string Title
  67. {
  68. get => _title;
  69. set => SetProperty(ref _title, value);
  70. }
  71. private BitmapSource _currentImage;
  72. /// <summary>
  73. /// 当前用于显示的 WPF 位图(从 OpenCV Mat 转换)。
  74. /// 该属性用于 UI 绑定,显示加载或绘制结果图像。
  75. /// </summary>
  76. public BitmapSource CurrentImage
  77. {
  78. get => _currentImage;
  79. set => SetProperty(ref _currentImage, value);
  80. }
  81. private AnalysisParameters _parameters;
  82. /// <summary>
  83. /// 分析参数集合(例如:聚焦方法、分析模式、是否实时分析等)。
  84. /// 外部可以通过绑定修改这些参数以影响分析行为。
  85. /// </summary>
  86. public AnalysisParameters Parameters
  87. {
  88. get => _parameters;
  89. set => SetProperty(ref _parameters, value);
  90. }
  91. private AnalysisResult _currentResult;
  92. /// <summary>
  93. /// 当前最新一次分析的结果(包含清晰度、对比度、质量评分等)。
  94. /// 供 UI 显示分析数值。
  95. /// </summary>
  96. public AnalysisResult CurrentResult
  97. {
  98. get => _currentResult;
  99. set => SetProperty(ref _currentResult, value);
  100. }
  101. private RoiModel _currentRoi;
  102. /// <summary>
  103. /// 当前定义的 ROI(来自 UI),表示要分析的图像区域(以画布坐标表示)。
  104. /// </summary>
  105. public RoiModel CurrentRoi
  106. {
  107. get => _currentRoi;
  108. set => SetProperty(ref _currentRoi, value);
  109. }
  110. private ChessboardInfo _chessboardInfo;
  111. /// <summary>
  112. /// 棋盘格检测信息(是否检测到、角点数组、包围矩形等)。
  113. /// 检测成功后可用于限定分析区域或在图像上绘制棋盘格。
  114. /// </summary>
  115. public ChessboardInfo ChessboardInfo
  116. {
  117. get => _chessboardInfo;
  118. set => SetProperty(ref _chessboardInfo, value);
  119. }
  120. private RoiOperationMode _roiMode;
  121. /// <summary>
  122. /// ROI 操作模式(绘制、移动、缩放等),由 UI 控制。
  123. /// </summary>
  124. public RoiOperationMode RoiMode
  125. {
  126. get => _roiMode;
  127. set => SetProperty(ref _roiMode, value);
  128. }
  129. private string _statusText;
  130. /// <summary>
  131. /// 状态文本,用于在 UI 中显示当前操作或错误信息。
  132. /// </summary>
  133. public string StatusText
  134. {
  135. get => _statusText;
  136. set => SetProperty(ref _statusText, value);
  137. }
  138. private bool _isAnalyzing;
  139. /// <summary>
  140. /// 指示是否正在进行实时分析(用于启用/禁用命令)。
  141. /// </summary>
  142. public bool IsAnalyzing
  143. {
  144. get => _isAnalyzing;
  145. set => SetProperty(ref _isAnalyzing, value);
  146. }
  147. private PlotModel _plotModel;
  148. /// <summary>
  149. /// OxyPlot 的 PlotModel,用于在 UI 中绘制清晰度趋势图。
  150. /// </summary>
  151. public PlotModel PlotModel
  152. {
  153. get => _plotModel;
  154. set => SetProperty(ref _plotModel, value);
  155. }
  156. private double _bestSharpness;
  157. /// <summary>
  158. /// 最佳清晰度值(内部字段)。BestSharpnessText 为其格式化显示。
  159. /// </summary>
  160. public string BestSharpnessText => _bestSharpness > 0 ? $"{_bestSharpness:F2}" : "N/A";
  161. private int _frameCount;
  162. /// <summary>
  163. /// 已分析的帧数文本(格式化)。
  164. /// </summary>
  165. public string FrameCountText => string.Format(Lang.帧数0, _frameCount);
  166. /// <summary>
  167. /// 支持的清晰度计算方法集合(用于 UI 下拉选择)。
  168. /// </summary>
  169. public ObservableCollection<FocusMethod> FocusMethods { get; }
  170. /// <summary>
  171. /// 支持的分析模式集合(用于 UI 下拉选择)。
  172. /// </summary>
  173. public ObservableCollection<AnalysisMode> AnalysisModes { get; }
  174. private ObservableCollection<CameraInfo> _CameraList;
  175. public ObservableCollection<CameraInfo> CameraList
  176. {
  177. get { return _CameraList; }
  178. set { SetProperty(ref _CameraList, value); }
  179. }
  180. private CameraInfo _SelectedCamera;
  181. public CameraInfo SelectedCamera
  182. {
  183. get { return _SelectedCamera; }
  184. set { SetProperty(ref _SelectedCamera, value);
  185. if (value!=null)
  186. {
  187. if (Camera != null)
  188. {
  189. Camera.ImageCallbackEvent -= Camera_ImageCallbackEvent;
  190. //Camera.Grab();
  191. }
  192. Camera = _cameraService.GetCamera(value.Id);
  193. Camera.ImageCallbackEvent += Camera_ImageCallbackEvent;
  194. try
  195. {
  196. var image = Camera.Grab();
  197. if (image==null)
  198. {
  199. return;
  200. }
  201. _currentMat = ImageHelper.ICogImageConvertMat(image);
  202. // 转换为 WPF 可显示的位图并更新 UI 绑定
  203. CurrentImage = _currentMat.ToBitmapSource();
  204. }
  205. catch (Exception)
  206. {
  207. }
  208. }
  209. else
  210. {
  211. Camera = null;
  212. }
  213. }
  214. }
  215. private ICamera Camera;
  216. #endregion
  217. #region 命令
  218. /// <summary>
  219. /// 加载图像命令(弹出文件对话并加载图像)。
  220. /// </summary>
  221. public DelegateCommand LoadImageCommand { get; }
  222. /// <summary>
  223. /// 开始分析命令(支持实时和一次性分析)。
  224. /// </summary>
  225. public DelegateCommand StartAnalysisCommand { get; }
  226. /// <summary>
  227. /// 停止实时分析命令。
  228. /// </summary>
  229. public DelegateCommand StopAnalysisCommand { get; }
  230. /// <summary>
  231. /// 重置所有统计与图表的命令。
  232. /// </summary>
  233. public DelegateCommand ResetCommand { get; }
  234. /// <summary>
  235. /// 导出历史分析结果为 CSV 的命令。
  236. /// </summary>
  237. public DelegateCommand ExportCommand { get; }
  238. /// <summary>
  239. /// 清除当前 ROI 的命令。
  240. /// </summary>
  241. public DelegateCommand ClearRoiCommand { get; }
  242. /// <summary>
  243. /// 检测棋盘格的命令(在当前图像或 ROI 上检测)。
  244. /// </summary>
  245. public DelegateCommand DetectChessboardCommand { get; }
  246. #endregion
  247. /// <summary>
  248. /// 构造函数:注入必要服务并初始化命令、绘图和定时器。
  249. /// </summary>
  250. /// <param name="eventAggregator">事件聚合器(用于模块间通信)</param>
  251. /// <param name="configService">配置服务</param>
  252. /// <param name="cameraService">相机服务</param>
  253. public FocusAnalyzerViewModel(IEventAggregator eventAggregator, IConfigService configService, ICameraService cameraService)
  254. {
  255. _eventAggregator = eventAggregator;
  256. _configService = configService;
  257. _cameraService = cameraService;
  258. _fileDialogService = new FileDialogService();
  259. _imageAnalysisService = new ImageAnalysisService();
  260. _checkerboardService = new CheckerboardDetectionService();
  261. _parameters = new AnalysisParameters();
  262. _currentResult = new AnalysisResult();
  263. _currentRoi = new RoiModel();
  264. _resultHistory = new List<AnalysisResult>();
  265. _roiMode = RoiOperationMode.Draw; // 默认为绘制模式
  266. // 初始化可枚举集合用于 UI 绑定
  267. FocusMethods = new ObservableCollection<FocusMethod>(Enum.GetValues(typeof(FocusMethod)).Cast<FocusMethod>());
  268. AnalysisModes = new ObservableCollection<AnalysisMode>(Enum.GetValues(typeof(AnalysisMode)).Cast<AnalysisMode>());
  269. // 初始化命令并绑定 CanExecute/ObservesProperty
  270. LoadImageCommand = new DelegateCommand(OnLoadImage);
  271. StartAnalysisCommand = new DelegateCommand(OnStartAnalysis, CanStartAnalysis).ObservesProperty(()=>SelectedCamera).ObservesProperty(() => IsAnalyzing);
  272. StopAnalysisCommand = new DelegateCommand(OnStopAnalysis, () => IsAnalyzing).ObservesProperty(() => IsAnalyzing);
  273. ResetCommand = new DelegateCommand(OnReset);
  274. ExportCommand = new DelegateCommand(OnExport, () => _resultHistory.Count > 0);
  275. ClearRoiCommand = new DelegateCommand(OnClearRoi);
  276. DetectChessboardCommand = new DelegateCommand(OnDetectChessboard, () => _currentMat != null);
  277. InitializePlot();
  278. // 分析定时器(用于实时分析)
  279. _analysisTimer = new DispatcherTimer
  280. {
  281. Interval = TimeSpan.FromMilliseconds(100)
  282. };
  283. _analysisTimer.Tick += OnAnalysisTick;
  284. StatusText = Lang.就绪;
  285. _eventAggregator.GetEvent<MainTabSwitchNotification>().Subscribe((index) =>
  286. {
  287. if (index != 2)
  288. {
  289. try
  290. {
  291. if (Camera != null)
  292. {
  293. Camera.ImageCallbackEvent -= Camera_ImageCallbackEvent;
  294. SelectedCamera = null;
  295. }
  296. }
  297. catch (Exception)
  298. {
  299. }
  300. }
  301. });
  302. }
  303. #region 方法
  304. /// <summary>
  305. /// 加载图像(通过文件对话框),并在加载后尝试自动检测棋盘格和/或触发实时分析。
  306. /// 异常会被捕获并通过 StatusText 通知 UI。
  307. /// </summary>
  308. private void OnLoadImage()
  309. {
  310. try
  311. {
  312. string filePath = _fileDialogService.OpenImageFile();
  313. if (string.IsNullOrEmpty(filePath))
  314. return;
  315. // 释放之前的图像以防内存泄漏
  316. _currentMat?.Dispose();
  317. // 从磁盘读取图像(彩色)
  318. _currentMat = Cv2.ImRead(filePath, ImreadModes.Color);
  319. if (_currentMat == null || _currentMat.Empty())
  320. {
  321. StatusText = Lang.无法加载图像;
  322. return;
  323. }
  324. // 转换为 WPF 可显示的位图并更新 UI 绑定
  325. CurrentImage = _currentMat.ToWriteableBitmap();
  326. // 自动检测棋盘格(异步)
  327. OnDetectChessboard();
  328. // 如果配置为实时分析,则立即进行一次分析(无需等待定时器)
  329. if (Parameters.EnableRealtimeAnalysis)
  330. {
  331. AnalyzeCurrentImage();
  332. }
  333. StatusText = string.Format(Lang.图像已加载0x1, _currentMat.Width, _currentMat.Height);
  334. }
  335. catch (Exception ex)
  336. {
  337. StatusText = string.Format(Lang.加载图像失败0, ex.Message);//$"加载图像失败: {ex.Message}";
  338. }
  339. }
  340. /// <summary>
  341. /// 在当前图像或当前 ROI 上检测棋盘格(异步执行检测以避免阻塞 UI)。
  342. /// 检测到后会将角点坐标从子图像坐标转换回全图坐标并在图片上绘制结果。
  343. /// </summary>
  344. private void OnDetectChessboard()
  345. {
  346. if (_currentMat == null || _currentMat.Empty())
  347. return;
  348. try
  349. {
  350. StatusText = Lang.正在检测棋盘格;
  351. Task.Run(() =>
  352. {
  353. ChessboardInfo info = null;
  354. // 优先在用户选定的 ROI 内检测
  355. if (RoiToImageRectConverter != null && CurrentRoi?.IsValid == true)
  356. {
  357. var imgRoi = RoiToImageRectConverter(CurrentRoi);
  358. if (imgRoi.HasValue)
  359. {
  360. using (var sub = new Mat(_currentMat, imgRoi.Value))
  361. {
  362. info = _checkerboardService.DetectChessboard(sub);
  363. }
  364. // 如果在子图中检测到角点,需要将角点坐标偏移回全图坐标
  365. if (info != null && info.IsDetected)
  366. {
  367. for (int i = 0; i < info.Corners.Length; i++)
  368. {
  369. info.Corners[i].X += imgRoi.Value.X;
  370. info.Corners[i].Y += imgRoi.Value.Y;
  371. }
  372. var br = info.BoundingRect;
  373. info.BoundingRect = new OpenCvSharp.Rect(br.X + imgRoi.Value.X, br.Y + imgRoi.Value.Y, br.Width, br.Height);
  374. }
  375. }
  376. }
  377. // 如果 ROI 内未检测到,则在整张图上检测
  378. if (info == null || !info.IsDetected)
  379. {
  380. info = _checkerboardService.DetectChessboard(_currentMat);
  381. }
  382. // 回到 UI 线程更新绑定与显示
  383. System.Windows.Application.Current.Dispatcher.Invoke(() =>
  384. {
  385. ChessboardInfo = info;
  386. if (info.IsDetected)
  387. {
  388. StatusText = string.Format(Lang.检测成功0x1角点, info.CornersWidth, info.CornersHeight);//$"检测成功: {info.CornersWidth}x{info.CornersHeight} 角点";
  389. // 在图像上绘制检测到的棋盘并更新 CurrentImage
  390. var displayMat = _currentMat.Clone();
  391. _checkerboardService.DrawChessboard(displayMat, info);
  392. CurrentImage = displayMat.ToWriteableBitmap();
  393. displayMat.Dispose();
  394. }
  395. else
  396. {
  397. StatusText = Lang.未检测到棋盘格;
  398. }
  399. });
  400. });
  401. }
  402. catch (Exception ex)
  403. {
  404. StatusText = string.Format(Lang.检测失败0, ex.Message);
  405. }
  406. }
  407. /// <summary>
  408. /// 判断是否可以开始分析:需要有当前图像且当前没有正在分析。
  409. /// </summary>
  410. /// <returns>如果可以开始分析返回 true,否则 false。</returns>
  411. private bool CanStartAnalysis()
  412. {
  413. return SelectedCamera != null && !IsAnalyzing;
  414. //return CurrentImage != null && !IsAnalyzing;
  415. }
  416. /// <summary>
  417. /// 开始分析流程。
  418. /// - 重置统计(帧数、最佳值、历史)
  419. /// - 根据是否启用实时分析决定启动定时器或直接分析一次
  420. /// </summary>
  421. private void OnStartAnalysis()
  422. {
  423. if (Camera==null)
  424. {
  425. return;
  426. }
  427. IsAnalyzing = true;
  428. _frameCount = 0;
  429. _bestSharpness = 0;
  430. _resultHistory.Clear();
  431. StatusText = Lang.分析中;
  432. if (Parameters.EnableRealtimeAnalysis)
  433. {
  434. //_analysisTimer.Start();
  435. Camera.StartGrabbing();
  436. }
  437. else
  438. {
  439. var image = Camera.Grab();
  440. _currentMat = ImageHelper.ICogImageConvertMat(image);
  441. // 转换为 WPF 可显示的位图并更新 UI 绑定
  442. CurrentImage = _currentMat.ToBitmapSource();
  443. AnalyzeCurrentImage();
  444. IsAnalyzing = false;
  445. StatusText = Lang.分析完成;
  446. }
  447. }
  448. /// <summary>
  449. /// 停止实时分析:停止定时器并更新状态。
  450. /// </summary>
  451. private void OnStopAnalysis()
  452. {
  453. if (Camera == null)
  454. {
  455. return;
  456. }
  457. if (Camera.IsGrabbing)
  458. {
  459. Camera.StopGrabbing();
  460. }
  461. //_analysisTimer.Stop();
  462. IsAnalyzing = false;
  463. StatusText = Lang.已停止;
  464. }
  465. /// <summary>
  466. /// 定时器回调:周期性触发一次图像分析。
  467. /// </summary>
  468. private void OnAnalysisTick(object sender, EventArgs e)
  469. {
  470. AnalyzeCurrentImage();
  471. }
  472. /// <summary>
  473. /// 执行一次图像分析:
  474. /// - 根据 AnalysisMode 决定使用 ROI、棋盘格或全图进行分析
  475. /// - 调用 ImageAnalysisService 执行具体分析
  476. /// - 更新 CurrentResult、历史、统计与趋势图
  477. /// </summary>
  478. private void AnalyzeCurrentImage()
  479. {
  480. if (_currentMat == null || _currentMat.Empty())
  481. return;
  482. try
  483. {
  484. Rect? roi = null;
  485. // 根据分析模式确定分析区域
  486. switch (Parameters.AnalysisMode)
  487. {
  488. case AnalysisMode.RoiOnly:
  489. if (CurrentRoi.IsValid)
  490. {
  491. if (RoiToImageRectConverter != null)
  492. {
  493. roi = RoiToImageRectConverter(CurrentRoi);
  494. }
  495. else
  496. {
  497. // 如果未提供转换器,则直接按 RoiModel 的像素值构建(视为已是像素)
  498. roi = new Rect(
  499. (int)CurrentRoi.X,
  500. (int)CurrentRoi.Y,
  501. (int)CurrentRoi.Width,
  502. (int)CurrentRoi.Height);
  503. }
  504. }
  505. break;
  506. case AnalysisMode.ChessboardOnly:
  507. if (ChessboardInfo?.IsDetected == true)
  508. {
  509. roi = ChessboardInfo.BoundingRect;
  510. }
  511. break;
  512. }
  513. // 执行实际图像分析并获取结果
  514. var result = _imageAnalysisService.AnalyzeImage(_currentMat, Parameters.FocusMethod, roi);
  515. // 更新当前结果与历史记录
  516. CurrentResult = result;
  517. _resultHistory.Add(result);
  518. _frameCount++;
  519. // 更新最佳清晰度并通知绑定
  520. if (result.Sharpness > _bestSharpness)
  521. {
  522. _bestSharpness = result.Sharpness;
  523. RaisePropertyChanged(nameof(BestSharpnessText));
  524. }
  525. // 更新帧数显示
  526. RaisePropertyChanged(nameof(FrameCountText));
  527. // 更新图表数据
  528. UpdatePlot();
  529. StatusText = string.Format(Lang.清晰度0对比度1, result.Sharpness, result.Contrast);
  530. }
  531. catch (Exception ex)
  532. {
  533. StatusText = string.Format(Lang.分析错误0, ex.Message);
  534. }
  535. }
  536. /// <summary>
  537. /// 重置所有统计数据与图表,停止分析。
  538. /// </summary>
  539. private void OnReset()
  540. {
  541. OnStopAnalysis();
  542. _frameCount = 0;
  543. _bestSharpness = 0;
  544. _resultHistory.Clear();
  545. CurrentResult = new AnalysisResult();
  546. InitializePlot();
  547. StatusText = Lang.已重置;
  548. RaisePropertyChanged(nameof(BestSharpnessText));
  549. RaisePropertyChanged(nameof(FrameCountText));
  550. }
  551. /// <summary>
  552. /// 导出历史分析结果为 CSV 文件。使用 FileDialogService 获取保存路径。
  553. /// </summary>
  554. private void OnExport()
  555. {
  556. try
  557. {
  558. string filePath = _fileDialogService.SaveFile(
  559. string.Format(Lang.分析报告0csv, DateTime.Now),
  560. "CSV文件|*.csv|所有文件|*.*");
  561. if (string.IsNullOrEmpty(filePath))
  562. return;
  563. using (var writer = new System.IO.StreamWriter(filePath))
  564. {
  565. writer.WriteLine(Lang.时间清晰度对比度质量评分);
  566. foreach (var result in _resultHistory)
  567. {
  568. writer.WriteLine($"{result.Timestamp:yyyy-MM-dd HH:mm:ss.fff},{result.Sharpness:F2},{result.Contrast:F2},{result.QualityScore:F2}");
  569. }
  570. }
  571. StatusText = string.Format(Lang.报告已导出0, filePath);
  572. }
  573. catch (Exception ex)
  574. {
  575. StatusText = string.Format(Lang.导出失败0, ex.Message);
  576. }
  577. }
  578. /// <summary>
  579. /// 清除当前 ROI(重置为默认),并通知 UI。
  580. /// </summary>
  581. private void OnClearRoi()
  582. {
  583. CurrentRoi = new RoiModel();
  584. StatusText = Lang.ROI已清除;
  585. }
  586. /// <summary>
  587. /// 初始化 OxyPlot 的 PlotModel(坐标轴与清晰度折线序列)。
  588. /// </summary>
  589. private void InitializePlot()
  590. {
  591. PlotModel = new PlotModel
  592. {
  593. Title = Lang.清晰度趋势,
  594. Background = OxyColors.White
  595. };
  596. PlotModel.Axes.Add(new LinearAxis
  597. {
  598. Position = AxisPosition.Bottom,
  599. Title = Lang.帧数,
  600. MajorGridlineStyle = LineStyle.Solid,
  601. MinorGridlineStyle = LineStyle.Dot,
  602. MajorGridlineColor = OxyColor.FromRgb(230, 230, 230)
  603. });
  604. PlotModel.Axes.Add(new LinearAxis
  605. {
  606. Position = AxisPosition.Left,
  607. Title = Lang.清晰度,
  608. MajorGridlineStyle = LineStyle.Solid,
  609. MinorGridlineStyle = LineStyle.Dot,
  610. MajorGridlineColor = OxyColor.FromRgb(230, 230, 230)
  611. });
  612. var series = new LineSeries
  613. {
  614. Title = Lang.清晰度,
  615. Color = OxyColor.FromRgb(0, 122, 204),
  616. StrokeThickness = 2,
  617. MarkerType = MarkerType.Circle,
  618. MarkerSize = 3,
  619. MarkerFill = OxyColor.FromRgb(0, 122, 204)
  620. };
  621. PlotModel.Series.Add(series);
  622. }
  623. /// <summary>
  624. /// 用于根据历史结果更新趋势图。会清空旧点并重新添加所有点,然后刷新绘图。
  625. /// </summary>
  626. private void UpdatePlot()
  627. {
  628. if (PlotModel.Series.Count == 0)
  629. return;
  630. var series = PlotModel.Series[0] as LineSeries;
  631. if (series == null)
  632. return;
  633. // 先清空已有点(保持序列样式不变)
  634. series.Points.Clear();
  635. // 将历史清晰度数据逐点加入序列(X 为帧索引,Y 为清晰度)
  636. for (int i = 0; i < _resultHistory.Count; i++)
  637. {
  638. series.Points.Add(new OxyPlot.DataPoint(i + 1, _resultHistory[i].Sharpness));
  639. }
  640. // 通知 PlotModel 重绘
  641. PlotModel.InvalidatePlot(true);
  642. }
  643. /// <summary>
  644. ///
  645. /// </summary>
  646. /// <param name="image"></param>
  647. /// <param name="totaltime"></param>
  648. /// <param name="errormessage"></param>
  649. private void Camera_ImageCallbackEvent(ICogImage image, TimeSpan totaltime, string errormessage)
  650. {
  651. _currentMat= ImageHelper.ICogImageConvertMat(image);
  652. App.Current.Dispatcher.Invoke(() =>
  653. {
  654. // 转换为 WPF 可显示的位图并更新 UI 绑定
  655. CurrentImage = _currentMat.ToBitmapSource();
  656. });
  657. AnalyzeCurrentImage();
  658. }
  659. #endregion
  660. #region 继承
  661. /// <summary>
  662. /// 导航请求确认(Prism INavigationAware)。
  663. /// 永远允许导航离开/进入(可以在需要时扩展为提示保存或取消操作)。
  664. /// </summary>
  665. public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
  666. {
  667. continuationCallback(true);
  668. }
  669. /// <summary>
  670. /// 导航到达时调用(可用于加载外部资源或初始化通道等)。
  671. /// 当前保留为异步签名,便于以后扩展异步加载逻辑。
  672. /// </summary>
  673. public async void OnNavigatedTo(NavigationContext navigationContext)
  674. {
  675. // TODO: 需要时从灯管理服务加载通道或其他初始化逻辑
  676. CameraList = new ObservableCollection<CameraInfo>(_configService.GetAllCameras());
  677. }
  678. /// <summary>
  679. /// 指示此实例是否作为目标处理此导航请求(通常返回 true)。
  680. /// </summary>
  681. /// <returns>如果为导航目标返回 true,否则 false。</returns>
  682. public bool IsNavigationTarget(NavigationContext navigationContext)
  683. {
  684. return true;
  685. }
  686. /// <summary>
  687. /// 导航离开时调用(可用于清理资源或停止定时器)。
  688. /// </summary>
  689. public void OnNavigatedFrom(NavigationContext navigationContext)
  690. {
  691. // nothing
  692. if (Camera != null)
  693. {
  694. if (IsAnalyzing)
  695. {
  696. OnStopAnalysis();
  697. }
  698. Camera.ImageCallbackEvent -= Camera_ImageCallbackEvent;
  699. //Camera.Grab();
  700. }
  701. }
  702. #endregion
  703. }
  704. }