FocusAnalyzerControl.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. using OpenCvSharp;
  2. using OpenCvSharp.WpfExtensions;
  3. using OxyPlot;
  4. using OxyPlot.Axes;
  5. using OxyPlot.Series;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.ComponentModel;
  10. using System.Linq;
  11. using System.Runtime.CompilerServices;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using System.Windows;
  15. using System.Windows.Controls;
  16. using System.Windows.Data;
  17. using System.Windows.Documents;
  18. using System.Windows.Input;
  19. using System.Windows.Media;
  20. using System.Windows.Media.Imaging;
  21. using System.Windows.Navigation;
  22. using System.Windows.Shapes;
  23. using TeamAAS_VP.Core;
  24. using TeamAAS_VP.Enums;
  25. using TeamAAS_VP.Models;
  26. using OpenCvSharp.Extensions;
  27. using Rect = OpenCvSharp.Rect;
  28. using DataPoint = TeamAAS_VP.Models.DataPoint;
  29. namespace TeamAAS_VP.Controls
  30. {
  31. /// <summary>
  32. /// FocusAnalyzerControl.xaml 的交互逻辑
  33. /// </summary>
  34. public partial class FocusAnalyzerControl : UserControl, INotifyPropertyChanged
  35. {
  36. // 命令
  37. public ICommand StartCommand { get; set; }
  38. public ICommand StopCommand { get; set; }
  39. public ICommand ResetCommand { get; set; }
  40. public ICommand ExportCommand { get; set; }
  41. // 可绑定属性
  42. private ImageSource _currentImage;
  43. private AnalysisParameters _parameters;
  44. private AnalysisResult _currentResult;
  45. private AnalysisReport _finalReport;
  46. private bool _isAnalyzing;
  47. private Rect? _currentRoi;
  48. private PlotModel _plotModel;
  49. // 内部状态
  50. private List<DataPoint> _historyData = new List<DataPoint>();
  51. private int _frameCounter = 0;
  52. private double _bestSharpness = 0;
  53. private DateTime _startTime;
  54. // 枚举值列表(用于ComboBox绑定)
  55. public Array FocusMethods => Enum.GetValues(typeof(FocusMethod));
  56. public Array AnalysisModes => Enum.GetValues(typeof(AnalysisMode));
  57. public ImageSource CurrentImage
  58. {
  59. get => _currentImage;
  60. set => SetField(ref _currentImage, value);
  61. }
  62. public AnalysisParameters Parameters
  63. {
  64. get => _parameters;
  65. set => SetField(ref _parameters, value);
  66. }
  67. public AnalysisResult CurrentResult
  68. {
  69. get => _currentResult;
  70. set => SetField(ref _currentResult, value);
  71. }
  72. public AnalysisReport FinalReport
  73. {
  74. get => _finalReport;
  75. set => SetField(ref _finalReport, value);
  76. }
  77. public bool IsAnalyzing
  78. {
  79. get => _isAnalyzing;
  80. set => SetField(ref _isAnalyzing, value);
  81. }
  82. public Rect? CurrentRoi
  83. {
  84. get => _currentRoi;
  85. set => SetField(ref _currentRoi, value);
  86. }
  87. public PlotModel PlotModel
  88. {
  89. get => _plotModel;
  90. set => SetField(ref _plotModel, value);
  91. }
  92. public FocusAnalyzerControl()
  93. {
  94. InitializeComponent();
  95. InitializeCommands();
  96. InitializeProperties();
  97. InitializePlot();
  98. DataContext = this;
  99. }
  100. private void InitializeCommands()
  101. {
  102. StartCommand = new RelayCommand(
  103. execute: StartAnalysis,
  104. canExecute: () => !IsAnalyzing);
  105. StopCommand = new RelayCommand(
  106. execute: StopAnalysis,
  107. canExecute: () => IsAnalyzing);
  108. ResetCommand = new RelayCommand(
  109. execute: ResetAnalysis);
  110. ExportCommand = new RelayCommand(
  111. execute: ExportReport);
  112. }
  113. private void InitializeProperties()
  114. {
  115. Parameters = new AnalysisParameters();
  116. CurrentResult = new AnalysisResult();
  117. FinalReport = new AnalysisReport();
  118. // 设置默认ROI
  119. CurrentRoi = null;
  120. }
  121. private void InitializePlot()
  122. {
  123. PlotModel = new PlotModel
  124. {
  125. Title = "清晰度变化曲线",
  126. TitleFontSize = 12,
  127. PlotMargins = new OxyThickness(40, 10, 10, 40)
  128. };
  129. // X轴
  130. PlotModel.Axes.Add(new LinearAxis
  131. {
  132. Position = AxisPosition.Bottom,
  133. Title = "帧序列",
  134. MajorGridlineStyle = LineStyle.Solid,
  135. MinorGridlineStyle = LineStyle.Dot,
  136. MajorGridlineColor = OxyColor.FromArgb(40, 0, 0, 0),
  137. MinorGridlineColor = OxyColor.FromArgb(20, 0, 0, 0)
  138. });
  139. // Y轴
  140. PlotModel.Axes.Add(new LinearAxis
  141. {
  142. Position = AxisPosition.Left,
  143. Title = "清晰度",
  144. MajorGridlineStyle = LineStyle.Solid,
  145. MinorGridlineStyle = LineStyle.Dot,
  146. MajorGridlineColor = OxyColor.FromArgb(40, 0, 0, 0),
  147. MinorGridlineColor = OxyColor.FromArgb(20, 0, 0, 0)
  148. });
  149. // 清晰度曲线
  150. var sharpnessSeries = new LineSeries
  151. {
  152. Title = "清晰度",
  153. Color = OxyColors.DodgerBlue,
  154. StrokeThickness = 2,
  155. MarkerType = MarkerType.Circle,
  156. MarkerSize = 3,
  157. MarkerFill = OxyColors.DodgerBlue,
  158. MarkerStroke = OxyColors.White,
  159. MarkerStrokeThickness = 1
  160. };
  161. PlotModel.Series.Add(sharpnessSeries);
  162. }
  163. /// <summary>
  164. /// 开始分析(由外部调用)
  165. /// </summary>
  166. public void StartAnalysis()
  167. {
  168. try
  169. {
  170. IsAnalyzing = true;
  171. _frameCounter = 0;
  172. _bestSharpness = 0;
  173. _historyData.Clear();
  174. _startTime = DateTime.Now;
  175. // 清空图表
  176. var series = PlotModel.Series[0] as LineSeries;
  177. series?.Points.Clear();
  178. // 初始化最终报告
  179. FinalReport = new AnalysisReport
  180. {
  181. Parameters = Parameters,
  182. StartTime = _startTime
  183. };
  184. // 更新UI
  185. UpdateStatus("分析中...");
  186. CommandManager.InvalidateRequerySuggested();
  187. }
  188. catch (Exception ex)
  189. {
  190. MessageBox.Show($"开始分析失败: {ex.Message}", "错误",
  191. MessageBoxButton.OK, MessageBoxImage.Error);
  192. }
  193. }
  194. /// <summary>
  195. /// 停止分析(由外部调用)
  196. /// </summary>
  197. public void StopAnalysis()
  198. {
  199. try
  200. {
  201. IsAnalyzing = false;
  202. // 完成报告
  203. FinalReport.EndTime = DateTime.Now;
  204. FinalReport.FinalResult = CurrentResult;
  205. FinalReport.HistoryData = new List<DataPoint>(_historyData);
  206. // 更新UI
  207. UpdateStatus("分析完成");
  208. CommandManager.InvalidateRequerySuggested();
  209. // 触发分析完成事件
  210. OnAnalysisCompleted();
  211. }
  212. catch (Exception ex)
  213. {
  214. MessageBox.Show($"停止分析失败: {ex.Message}", "错误",
  215. MessageBoxButton.OK, MessageBoxImage.Error);
  216. }
  217. }
  218. /// <summary>
  219. /// 重置分析
  220. /// </summary>
  221. public void ResetAnalysis()
  222. {
  223. Parameters.ResetToDefaults();
  224. CurrentResult = new AnalysisResult();
  225. FinalReport = new AnalysisReport();
  226. _historyData.Clear();
  227. _frameCounter = 0;
  228. _bestSharpness = 0;
  229. // 清空图表
  230. var series = PlotModel.Series[0] as LineSeries;
  231. series?.Points.Clear();
  232. PlotModel.InvalidatePlot(true);
  233. // 清空图像
  234. CurrentImage = null;
  235. UpdateStatus("已重置");
  236. }
  237. /// <summary>
  238. /// 导出报告
  239. /// </summary>
  240. private void ExportReport()
  241. {
  242. try
  243. {
  244. var saveDialog = new Microsoft.Win32.SaveFileDialog
  245. {
  246. Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
  247. FileName = $"相机分析报告_{DateTime.Now:yyyyMMdd_HHmmss}.txt"
  248. };
  249. if (saveDialog.ShowDialog() == true)
  250. {
  251. var report = FinalReport.GenerateTextReport();
  252. System.IO.File.WriteAllText(saveDialog.FileName, report);
  253. MessageBox.Show($"报告已保存到:{saveDialog.FileName}", "成功",
  254. MessageBoxButton.OK, MessageBoxImage.Information);
  255. }
  256. }
  257. catch (Exception ex)
  258. {
  259. MessageBox.Show($"导出失败:{ex.Message}", "错误",
  260. MessageBoxButton.OK, MessageBoxImage.Error);
  261. }
  262. }
  263. /// <summary>
  264. /// 处理新图像帧(由外部调用)
  265. /// </summary>
  266. public void ProcessImageFrame(Mat frame)
  267. {
  268. if (!IsAnalyzing || frame == null || frame.Empty())
  269. return;
  270. try
  271. {
  272. // 更新UI图像
  273. Application.Current.Dispatcher.Invoke(() =>
  274. {
  275. CurrentImage = BitmapSourceConverter.ToBitmapSource(frame);
  276. });
  277. // 执行分析
  278. PerformAnalysis(frame);
  279. _frameCounter++;
  280. }
  281. catch (Exception ex)
  282. {
  283. Console.WriteLine($"处理图像帧失败: {ex.Message}");
  284. }
  285. }
  286. /// <summary>
  287. /// 执行单次图像分析
  288. /// </summary>
  289. public void PerformAnalysis(Mat frame)
  290. {
  291. if (frame == null || frame.Empty())
  292. return;
  293. try
  294. {
  295. // 1. 计算清晰度
  296. double sharpness = FocusAnalysisEngine.CalculateImageSharpness(
  297. frame, Parameters.FocusMethod, CurrentRoi);
  298. // 2. 分析棋盘格
  299. CheckerboardResult checkerboard;
  300. if (Parameters.AnalysisMode == AnalysisMode.AutoCheckerboard)
  301. {
  302. checkerboard = FocusAnalysisEngine.AnalyzeCheckerboardContrast(frame, CurrentRoi);
  303. }
  304. else
  305. {
  306. checkerboard = new CheckerboardResult();
  307. }
  308. // 3. 计算质量评分
  309. double qualityScore = FocusAnalysisEngine.CalculateQualityScore(sharpness, checkerboard);
  310. // 4. 生成建议
  311. var suggestions = FocusAnalysisEngine.GenerateSuggestions(
  312. sharpness, checkerboard,
  313. Parameters.SharpnessThreshold,
  314. Parameters.ContrastThreshold);
  315. // 5. 更新最佳清晰度
  316. if (sharpness > _bestSharpness)
  317. {
  318. _bestSharpness = sharpness;
  319. }
  320. // 6. 更新结果
  321. Application.Current.Dispatcher.Invoke(() =>
  322. {
  323. CurrentResult.Sharpness = sharpness;
  324. CurrentResult.Checkerboard = checkerboard;
  325. CurrentResult.QualityScore = qualityScore;
  326. CurrentResult.FrameCount = _frameCounter + 1;
  327. CurrentResult.BestSharpness = _bestSharpness;
  328. CurrentResult.AnalysisTime = DateTime.Now;
  329. CurrentResult.Suggestions = new ObservableCollection<string>(suggestions);
  330. // 更新历史数据
  331. var dataPoint = new DataPoint(_frameCounter, sharpness,
  332. checkerboard.Detected ? checkerboard.Contrast : 0);
  333. _historyData.Add(dataPoint);
  334. // 更新图表
  335. UpdatePlot(dataPoint);
  336. // 更新状态文本
  337. UpdateStatusText();
  338. });
  339. }
  340. catch (Exception ex)
  341. {
  342. Console.WriteLine($"图像分析失败: {ex.Message}");
  343. }
  344. }
  345. private void UpdatePlot(DataPoint dataPoint)
  346. {
  347. var series = PlotModel.Series[0] as LineSeries;
  348. if (series != null)
  349. {
  350. series.Points.Add(new OxyPlot.DataPoint(dataPoint.FrameIndex, dataPoint.Sharpness));
  351. // 限制显示的点数(最多200个点)
  352. if (series.Points.Count > 200)
  353. {
  354. series.Points.RemoveAt(0);
  355. }
  356. PlotModel.InvalidatePlot(true);
  357. }
  358. }
  359. private void UpdateStatusText()
  360. {
  361. StatusText.Text = $"分析中... 第 {_frameCounter + 1} 帧";
  362. FrameCountText.Text = $"帧数: {_frameCounter + 1}";
  363. BestSharpnessText.Text = $"最佳: {_bestSharpness:F2}";
  364. }
  365. private void UpdateStatus(string status)
  366. {
  367. StatusText.Text = status;
  368. }
  369. // ROI绘制相关
  370. private bool _isDrawingRoi = false;
  371. private System.Windows.Point _roiStartPoint;
  372. private void ImageDisplay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  373. {
  374. if (CurrentImage == null) return;
  375. _roiStartPoint = e.GetPosition(ImageDisplay);
  376. _isDrawingRoi = true;
  377. RoiRectangle.Visibility = Visibility.Visible;
  378. Canvas.SetLeft(RoiRectangle, _roiStartPoint.X);
  379. Canvas.SetTop(RoiRectangle, _roiStartPoint.Y);
  380. RoiRectangle.Width = 0;
  381. RoiRectangle.Height = 0;
  382. }
  383. private void ImageDisplay_MouseMove(object sender, MouseEventArgs e)
  384. {
  385. if (!_isDrawingRoi) return;
  386. var currentPoint = e.GetPosition(ImageDisplay);
  387. double left = Math.Min(_roiStartPoint.X, currentPoint.X);
  388. double top = Math.Min(_roiStartPoint.Y, currentPoint.Y);
  389. double width = Math.Abs(currentPoint.X - _roiStartPoint.X);
  390. double height = Math.Abs(currentPoint.Y - _roiStartPoint.Y);
  391. Canvas.SetLeft(RoiRectangle, left);
  392. Canvas.SetTop(RoiRectangle, top);
  393. RoiRectangle.Width = width;
  394. RoiRectangle.Height = height;
  395. }
  396. private void ImageDisplay_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  397. {
  398. if (!_isDrawingRoi) return;
  399. _isDrawingRoi = false;
  400. var endPoint = e.GetPosition(ImageDisplay);
  401. // 转换为图像坐标
  402. if (CurrentImage is BitmapSource bitmapSource)
  403. {
  404. double scaleX = bitmapSource.PixelWidth / ImageDisplay.ActualWidth;
  405. double scaleY = bitmapSource.PixelHeight / ImageDisplay.ActualHeight;
  406. int x = (int)(Math.Min(_roiStartPoint.X, endPoint.X) * scaleX);
  407. int y = (int)(Math.Min(_roiStartPoint.Y, endPoint.Y) * scaleY);
  408. int width = (int)(Math.Abs(endPoint.X - _roiStartPoint.X) * scaleX);
  409. int height = (int)(Math.Abs(endPoint.Y - _roiStartPoint.Y) * scaleY);
  410. // 确保ROI在图像范围内
  411. x = Math.Max(0, Math.Min(x, bitmapSource.PixelWidth - 1));
  412. y = Math.Max(0, Math.Min(y, bitmapSource.PixelHeight - 1));
  413. width = Math.Max(1, Math.Min(width, bitmapSource.PixelWidth - x));
  414. height = Math.Max(1, Math.Min(height, bitmapSource.PixelHeight - y));
  415. CurrentRoi = new Rect(x, y, width, height);
  416. }
  417. }
  418. private void ImageDisplay_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
  419. {
  420. // 清除ROI
  421. CurrentRoi = null;
  422. RoiRectangle.Visibility = Visibility.Collapsed;
  423. }
  424. // INotifyPropertyChanged 实现
  425. public event PropertyChangedEventHandler PropertyChanged;
  426. protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  427. {
  428. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  429. }
  430. protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
  431. {
  432. if (EqualityComparer<T>.Default.Equals(field, value)) return false;
  433. field = value;
  434. OnPropertyChanged(propertyName);
  435. return true;
  436. }
  437. // 事件
  438. public event EventHandler AnalysisCompleted;
  439. protected virtual void OnAnalysisCompleted()
  440. {
  441. AnalysisCompleted?.Invoke(this, EventArgs.Empty);
  442. }
  443. }
  444. /// <summary>
  445. /// RelayCommand实现
  446. /// </summary>
  447. public class RelayCommand : ICommand
  448. {
  449. private readonly Action _execute;
  450. private readonly Func<bool> _canExecute;
  451. public event EventHandler CanExecuteChanged
  452. {
  453. add => CommandManager.RequerySuggested += value;
  454. remove => CommandManager.RequerySuggested -= value;
  455. }
  456. public RelayCommand(Action execute, Func<bool> canExecute = null)
  457. {
  458. _execute = execute ?? throw new ArgumentNullException(nameof(execute));
  459. _canExecute = canExecute;
  460. }
  461. public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
  462. public void Execute(object parameter) => _execute();
  463. }
  464. /// <summary>
  465. /// 布尔值到文本转换器
  466. /// </summary>
  467. public class BoolToTextConverter : System.Windows.Data.IValueConverter
  468. {
  469. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  470. {
  471. if (value is bool boolValue && parameter is string param)
  472. {
  473. var options = param.Split('|');
  474. return boolValue ? options[0] : options[1];
  475. }
  476. return string.Empty;
  477. }
  478. public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  479. {
  480. throw new NotImplementedException();
  481. }
  482. }
  483. }