MainWindow.xaml.cs 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  1. using AI.Common;
  2. using AI.Common.Log;
  3. using AI.DiagSystem;
  4. using AIDiagnosis.Common.Enums;
  5. using AIDiagnosis.Common.Interfaces;
  6. using AIDiagnosisDemo.GC;
  7. using AIDiagnosisDemo.Infrastucture;
  8. using AIDiagnosisDemo.Service;
  9. using AIDiagnosisDemo.Settings;
  10. using AIDiagnosisSDK.Enums;
  11. using MyocardialDiagnosisSDK;
  12. using MyocardialSegmentLib;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.ComponentModel;
  16. using System.Diagnostics;
  17. using System.Drawing;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using System.Windows;
  23. using System.Windows.Controls;
  24. using System.Windows.Media;
  25. using System.Windows.Threading;
  26. using ThyroidClassificationSDK;
  27. using ThyroidSectionClassificaionLib;
  28. using EnumThyroidSectionType = ThyroidSectionClassificaionLib.EnumThyroidSectionType;
  29. using Rectangle = System.Drawing.Rectangle;
  30. namespace AIDiagnosisDemo.Presentation
  31. {
  32. /// <summary>
  33. /// Interaction logic for MainWindow.xaml
  34. /// </summary>
  35. public partial class MainWindow : Window
  36. {
  37. private AIDiagnosisSDK.AIDiagnosis _diagnosis;
  38. private int _startTickCount;
  39. private bool _isPlaying;
  40. private Bitmap _image;
  41. private List<Roi> _rois;
  42. private List<Organ> _organs;
  43. private MyTransform _transform;
  44. private Dictionary<EnumOrgans, List<string>> _conclusions;
  45. private List<Array> _ramUsedList;
  46. private int _cpuUsed = 0;
  47. private int _ramUsed = 0;
  48. private PerformanceCounter _processRAMCounter;
  49. private PerformanceCounter _processCPUCounter;
  50. private Timer _usedStatustTimer;
  51. private double _ramSize;
  52. private List<Thread> _cpuThreads = new List<Thread>();
  53. private Task _ramThread = null;
  54. private List<string> _cycleImagesList = null;
  55. private Thread _cycleTestThread;
  56. private IPlayer _player;
  57. private IImageProvider _imageProvider;
  58. private MyocardialDiagnosis _myocardialDiagnosis;
  59. private DetectedObject _currentDetectedObject;
  60. private GCController _gcController;
  61. private IImageProvider _myocardialImageProvider;
  62. private IImageProvider _thyroidClassificationImageProvider;
  63. private ThyroidClassification _thyroidClassification;
  64. public MainWindow()
  65. {
  66. InitializeComponent();
  67. Logger.Info("Open the program!");
  68. GcAdapter.Instance.RegisterForFullGCNotification(99, 99);
  69. _gcController = new GCController();
  70. _ramSize = RAMHelper.ToFileFormat(RAMHelper.GetTotalPhysicalMemory(), FileSizeUnit.GB);
  71. var processName = Process.GetCurrentProcess().ProcessName;
  72. _processRAMCounter = new PerformanceCounter("Process", "Working Set", processName);
  73. _processCPUCounter = new PerformanceCounter("Process", "% Processor Time", processName);
  74. _usedStatustTimer = new Timer(TimerCallBack, null, Timeout.Infinite, 1000);//不启动,调用CallBack周期为1000ms.
  75. MaxButton.Visibility = Visibility.Collapsed;
  76. RestoreButton.Visibility = Visibility.Visible;
  77. InitializePlayer();
  78. PlayerManager.Instance.PlayerChanged += OnPlayerChanged;
  79. SettingConfig.Instance.ValueChangedEvent += OnValueChanged;
  80. OnValueChanged(null, new List<SettingProperty> { SettingProperty.IsSimulation, SettingProperty.IsEnableAI, SettingProperty.IsCycleImagesPlay });
  81. }
  82. private void InitializePlayer()
  83. {
  84. if (_player != null)
  85. {
  86. _player.Stop();
  87. _player.InputFrameReceived -= OnInputFrameReceived;
  88. _player.FPSChanged -= OnFPSChanged;
  89. }
  90. _player = PlayerManager.Instance.Player;
  91. if (_player != null)
  92. {
  93. _player.InputFrameReceived += OnInputFrameReceived;
  94. _player.FPSChanged += OnFPSChanged;
  95. _player.Play();
  96. _isPlaying = true;
  97. Dispatcher.Invoke(() =>
  98. {
  99. PlayButton.IsEnabled = SettingConfig.Instance.IsVideo;
  100. if (PlayButton.Visibility == Visibility.Visible)
  101. {
  102. PlayButton.Visibility = Visibility.Collapsed;
  103. }
  104. });
  105. }
  106. }
  107. private void OnPlayerChanged(object sender, EventArgs e)
  108. {
  109. if (_player != null)
  110. {
  111. //StopDiagnosis();
  112. CleanAIResult();
  113. _player.Stop();
  114. _player.InputFrameReceived -= OnInputFrameReceived;
  115. _player.FPSChanged -= OnFPSChanged;
  116. }
  117. _player = PlayerManager.Instance.Player;
  118. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Player Changed:{SettingConfig.Instance.UltrasoundImageSource}");
  119. if (_player != null)
  120. {
  121. _player.InputFrameReceived += OnInputFrameReceived;
  122. _player.FPSChanged += OnFPSChanged;
  123. _player.Play();
  124. _isPlaying = true;
  125. Dispatcher.Invoke(() =>
  126. {
  127. PlayButton.IsEnabled = SettingConfig.Instance.IsVideo;
  128. if (PlayButton.Visibility == Visibility.Visible)
  129. {
  130. PlayButton.Visibility = Visibility.Collapsed;
  131. }
  132. });
  133. if (SettingConfig.Instance.IsEnableAI)
  134. {
  135. StartDiagnosis();
  136. if (SettingConfig.Instance.IsVideo == false)//当源文件为图片的情况下,就重新Show一次给AI提供图片信息。
  137. {
  138. DetectImage();
  139. }
  140. }
  141. }
  142. }
  143. private void DetectImage()
  144. {
  145. if (_image != null)
  146. {
  147. if (_myocardialDiagnosis != null)
  148. {
  149. var rawImage = BitmapHelper.BitmapToRawImage(_image, true);
  150. _myocardialDiagnosis.DetectOneImage(rawImage, false);
  151. }
  152. else if (_thyroidClassification != null)
  153. {
  154. var rawImage = BitmapHelper.BitmapToRawImage(_image, true);
  155. _thyroidClassification.DetectOneImage(rawImage);
  156. }
  157. else
  158. {
  159. var rawImage = BitmapHelper.BitmapToRawImage(_image, true);
  160. _diagnosis.DetectOneImage(rawImage, true, true, true);
  161. }
  162. }
  163. }
  164. private void TimerCallBack(object state)
  165. {
  166. var processRAMUsedValue = Math.Round(_processRAMCounter.NextValue() / 1024 / 1024 / 1024, 2);
  167. var processCpuUsedValue = Math.Round(_processCPUCounter.NextValue(), 2);
  168. var ramUsedRate = Math.Round(processRAMUsedValue / _ramSize * 100, 2);
  169. var cpuUsedRate = Math.Round(processCpuUsedValue / Environment.ProcessorCount, 2);
  170. Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  171. {
  172. if (UsedStatusText.Visibility == Visibility.Collapsed)
  173. {
  174. UsedStatusText.Visibility = Visibility.Visible;
  175. }
  176. UsedStatusText.Text = $"当前CPU占用率: {cpuUsedRate}%\r\n当前内存占用率:{ramUsedRate}%,({processRAMUsedValue}GB/{_ramSize}GB) ";
  177. }));
  178. }
  179. private T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
  180. {
  181. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
  182. {
  183. var child = VisualTreeHelper.GetChild(obj, i);
  184. if (child is T variable)
  185. {
  186. return variable;
  187. }
  188. return FindVisualChild<T>(child);
  189. }
  190. return null;
  191. }
  192. private void RefreshUsedStatus()
  193. {
  194. if (SettingConfig.Instance.IsSimulation)
  195. {
  196. _usedStatustTimer.Change(0, 1000);
  197. if (_cpuUsed != SettingConfig.Instance.CPUUsed)
  198. {
  199. StopCPUUsed();
  200. StartCPUUsed();
  201. }
  202. if (_ramUsed != SettingConfig.Instance.RAMUsed)
  203. {
  204. StopRAMUsed();
  205. StartRAMUsed();
  206. }
  207. }
  208. else
  209. {
  210. _usedStatustTimer.Change(-1, 1000);
  211. Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  212. {
  213. if (UsedStatusText.Visibility == Visibility.Visible)
  214. {
  215. UsedStatusText.Visibility = Visibility.Collapsed;
  216. UsedStatusText.Text = "";
  217. }
  218. }));
  219. if (_cpuUsed != 0)
  220. {
  221. StopCPUUsed();
  222. }
  223. if (_ramUsed != 0)
  224. {
  225. StopRAMUsed();
  226. }
  227. }
  228. }
  229. private void OnOpenSettingWindow(object sender, RoutedEventArgs e)
  230. {
  231. var settingWindow = new SettingWindow();
  232. settingWindow.ShowDialog();
  233. }
  234. protected override void OnClosing(CancelEventArgs e)
  235. {
  236. PlayerManager.Instance.PlayerChanged -= OnPlayerChanged;
  237. PlayerManager.Instance.Dispose();
  238. if (_imageProvider != null)
  239. {
  240. ((ImageProvider)_imageProvider).Dispose();
  241. }
  242. StopPlay();
  243. CloseDiagnosis();
  244. CleanAIResult();
  245. SettingConfig.Instance.ValueChangedEvent -= OnValueChanged;
  246. StopCPUUsed();
  247. StopRAMUsed();
  248. _gcController.Close();
  249. Logger.Info("Close the program!");
  250. base.OnClosing(e);
  251. }
  252. private void StartDiagnosis()
  253. {
  254. switch (SettingConfig.Instance.AIDiagnosisType)
  255. {
  256. case AIDiagnosisType.Myocardial:
  257. if (_myocardialDiagnosis == null)
  258. {
  259. if (_myocardialImageProvider == null)
  260. {
  261. _myocardialImageProvider = new ImageProvider();
  262. }
  263. var cpuNumber = 1;
  264. switch (SettingConfig.Instance.Performance)
  265. {
  266. case EnumPerformance.Low:
  267. cpuNumber = 1;
  268. break;
  269. case EnumPerformance.Medium:
  270. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.4);
  271. break;
  272. case EnumPerformance.High:
  273. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.6);
  274. break;
  275. case EnumPerformance.Maximum:
  276. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.8);
  277. break;
  278. }
  279. var modelFileFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Networks");
  280. _myocardialDiagnosis = new MyocardialDiagnosis(false, false, null, _myocardialImageProvider, cpuNumber, modelFileFolder, EnumMyocardialInferWorkName.HumanMyocardialSegment, (EnumDetectMode)SettingConfig.Instance.DetectMode, SettingConfig.Instance.DetectTps, SettingConfig.Instance.IntervalTime);
  281. _myocardialDiagnosis.CompleteMyocardialImg = SettingConfig.Instance.CompleteMyocardialImg;
  282. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Initialize Diagnosis");
  283. }
  284. if (_myocardialDiagnosis != null)
  285. {
  286. _myocardialDiagnosis.StartEvaluation += OnStartEvaluation;
  287. _myocardialDiagnosis.FinishEvaluation += OnMyocardialFinishEvaluation;
  288. _myocardialDiagnosis.NotifyError += OnNotifyError;
  289. _myocardialDiagnosis.NotifyLog += OnNotifyLog;
  290. _myocardialDiagnosis.Start();
  291. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Start Diagnosis");
  292. }
  293. Dispatcher.Invoke(() =>
  294. {
  295. ExtractContoursBtn.Visibility = Visibility.Visible;
  296. });
  297. break;
  298. case AIDiagnosisType.MiceMyocardial:
  299. if (_myocardialDiagnosis == null)
  300. {
  301. if (_myocardialImageProvider == null)
  302. {
  303. _myocardialImageProvider = new ImageProvider();
  304. }
  305. var cpuNumber = 1;
  306. switch (SettingConfig.Instance.Performance)
  307. {
  308. case EnumPerformance.Low:
  309. cpuNumber = 1;
  310. break;
  311. case EnumPerformance.Medium:
  312. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.4);
  313. break;
  314. case EnumPerformance.High:
  315. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.6);
  316. break;
  317. case EnumPerformance.Maximum:
  318. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.8);
  319. break;
  320. }
  321. var modelFileFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Networks");
  322. _myocardialDiagnosis = new MyocardialDiagnosis(false, false, null, _myocardialImageProvider, cpuNumber, modelFileFolder, EnumMyocardialInferWorkName.MiceMyocardialSegment, (EnumDetectMode)SettingConfig.Instance.DetectMode, SettingConfig.Instance.DetectTps, SettingConfig.Instance.IntervalTime);
  323. _myocardialDiagnosis.CompleteMyocardialImg = SettingConfig.Instance.CompleteMyocardialImg;
  324. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Initialize Diagnosis");
  325. }
  326. if (_myocardialDiagnosis != null)
  327. {
  328. _myocardialDiagnosis.StartEvaluation += OnStartEvaluation;
  329. _myocardialDiagnosis.FinishEvaluation += OnMyocardialFinishEvaluation;
  330. _myocardialDiagnosis.NotifyError += OnNotifyError;
  331. _myocardialDiagnosis.NotifyLog += OnNotifyLog;
  332. _myocardialDiagnosis.Start();
  333. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Start Diagnosis");
  334. }
  335. Dispatcher.Invoke(() =>
  336. {
  337. ExtractContoursBtn.Visibility = Visibility.Visible;
  338. });
  339. break;
  340. case AIDiagnosisType.RatMyocardial:
  341. if (_myocardialDiagnosis == null)
  342. {
  343. if (_myocardialImageProvider == null)
  344. {
  345. _myocardialImageProvider = new ImageProvider();
  346. }
  347. var cpuNumber = 1;
  348. switch (SettingConfig.Instance.Performance)
  349. {
  350. case EnumPerformance.Low:
  351. cpuNumber = 1;
  352. break;
  353. case EnumPerformance.Medium:
  354. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.4);
  355. break;
  356. case EnumPerformance.High:
  357. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.6);
  358. break;
  359. case EnumPerformance.Maximum:
  360. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.8);
  361. break;
  362. }
  363. var modelFileFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Networks");
  364. _myocardialDiagnosis = new MyocardialDiagnosis(false, false, null, _myocardialImageProvider, cpuNumber, modelFileFolder, EnumMyocardialInferWorkName.RatMyocardialSegment, (EnumDetectMode)SettingConfig.Instance.DetectMode, SettingConfig.Instance.DetectTps, SettingConfig.Instance.IntervalTime);
  365. _myocardialDiagnosis.CompleteMyocardialImg = SettingConfig.Instance.CompleteMyocardialImg;
  366. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Initialize Diagnosis");
  367. }
  368. if (_myocardialDiagnosis != null)
  369. {
  370. _myocardialDiagnosis.StartEvaluation += OnStartEvaluation;
  371. _myocardialDiagnosis.FinishEvaluation += OnMyocardialFinishEvaluation;
  372. _myocardialDiagnosis.NotifyError += OnNotifyError;
  373. _myocardialDiagnosis.NotifyLog += OnNotifyLog;
  374. _myocardialDiagnosis.Start();
  375. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Start Diagnosis");
  376. }
  377. Dispatcher.Invoke(() =>
  378. {
  379. ExtractContoursBtn.Visibility = Visibility.Visible;
  380. });
  381. break;
  382. case AIDiagnosisType.Normal:
  383. case AIDiagnosisType.OrganIdentification:
  384. var aiModuleType = SettingConfig.Instance.AIDiagnosisType == AIDiagnosisType.Normal ? EnumAIModule.NotSpecified : EnumAIModule.OrganIdentification;
  385. Dispatcher.Invoke(() =>
  386. {
  387. ExtractContoursBtn.Visibility = Visibility.Collapsed;
  388. });
  389. if (_diagnosis == null)
  390. {
  391. if (_imageProvider == null)
  392. {
  393. _imageProvider = new ImageProvider();
  394. }
  395. bool enableLesionSeg;
  396. bool enableDescription;
  397. if (SettingConfig.Instance.DisplayType == EnumDisplayType.Border)
  398. {
  399. enableLesionSeg = false;
  400. enableDescription = false;
  401. }
  402. else
  403. {
  404. enableLesionSeg = true;
  405. enableDescription = true;
  406. }
  407. _diagnosis = new AIDiagnosisSDK.AIDiagnosis(aiModuleType, false, false, AppDomain.CurrentDomain.BaseDirectory, _imageProvider, SettingConfig.Instance.Performance, SettingConfig.Instance.DetectMode, !SettingConfig.Instance.CropImage, SettingConfig.Instance.DetectTps, SettingConfig.Instance.IntervalTime, "", enableLesionSeg, enableDescription, true, false, 0, 0, enableDescription);
  408. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Initialize Diagnosis");
  409. }
  410. if (_diagnosis != null)
  411. {
  412. _diagnosis.StartEvaluation += OnStartEvaluation;
  413. _diagnosis.FinishEvaluation += OnFinishEvaluation;
  414. _diagnosis.NotifyError += OnNotifyError;
  415. _diagnosis.NotifyLog += OnNotifyLog;
  416. _diagnosis.Start();
  417. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Start Diagnosis");
  418. }
  419. break;
  420. case AIDiagnosisType.ThyroidClassification:
  421. Dispatcher.Invoke(() =>
  422. {
  423. ExtractContoursBtn.Visibility = Visibility.Collapsed;
  424. });
  425. if (_thyroidClassification == null)
  426. {
  427. if (_thyroidClassificationImageProvider == null)
  428. {
  429. _thyroidClassificationImageProvider = new ImageProvider();
  430. }
  431. var cpuNumber = 1;
  432. switch (SettingConfig.Instance.Performance)
  433. {
  434. case EnumPerformance.Low:
  435. cpuNumber = 1;
  436. break;
  437. case EnumPerformance.Medium:
  438. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.4);
  439. break;
  440. case EnumPerformance.High:
  441. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.6);
  442. break;
  443. case EnumPerformance.Maximum:
  444. cpuNumber = (int)Math.Ceiling(Environment.ProcessorCount * 0.8);
  445. break;
  446. }
  447. var modelFileFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Networks");
  448. _thyroidClassification = new ThyroidClassification(cpuNumber, modelFileFolder, false, false, null, _thyroidClassificationImageProvider, SettingConfig.Instance.DetectMode, SettingConfig.Instance.DetectTps, SettingConfig.Instance.IntervalTime, true);
  449. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Initialize ThyroidClassificaion");
  450. }
  451. if (_thyroidClassification != null)
  452. {
  453. _thyroidClassification.StartEvaluation += OnStartEvaluation;
  454. _thyroidClassification.FinishEvaluation += OnThyroidClassificationFinishEvaluationNotification;
  455. _thyroidClassification.NotifyError += OnNotifyError;
  456. _thyroidClassification.Start();
  457. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Start ThyroidClassificaion");
  458. }
  459. Dispatcher.Invoke(() =>
  460. {
  461. ExtractContoursBtn.Visibility = Visibility.Visible;
  462. });
  463. break;
  464. }
  465. }
  466. private void OnNotifyLog(object sender, LogEventArgs e)
  467. {
  468. }
  469. private void OnNotifyError(object sender, ErrorEventArgs e)
  470. {
  471. Dispatcher.Invoke(() =>
  472. {
  473. ErrorInfoText.Text = "AI推理过程中发生错误:" + e.GetException();
  474. });
  475. }
  476. private void CloseDiagnosis()
  477. {
  478. if (_diagnosis != null)
  479. {
  480. _diagnosis.StartEvaluation -= OnStartEvaluation;
  481. _diagnosis.FinishEvaluation -= OnFinishEvaluation;
  482. _diagnosis.NotifyError -= OnNotifyError;
  483. _diagnosis.Close();
  484. _diagnosis = null;
  485. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Close Diagnosis");
  486. }
  487. if (_myocardialDiagnosis != null)
  488. {
  489. _myocardialDiagnosis.StartEvaluation -= OnStartEvaluation;
  490. _myocardialDiagnosis.NotifyError -= OnNotifyError;
  491. _myocardialDiagnosis.NotifyLog -= OnNotifyLog;
  492. _myocardialDiagnosis.FinishEvaluation -= OnMyocardialFinishEvaluation;
  493. _myocardialDiagnosis.Close();
  494. _myocardialDiagnosis = null;
  495. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Close Diagnosis");
  496. }
  497. if (_thyroidClassification != null)
  498. {
  499. _thyroidClassification.StartEvaluation -= OnStartEvaluation;
  500. _thyroidClassification.NotifyError -= OnNotifyError;
  501. _thyroidClassification.FinishEvaluation -= OnThyroidClassificationFinishEvaluationNotification;
  502. _thyroidClassification.Close();
  503. _thyroidClassification = null;
  504. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Close ThyroidClassificaion");
  505. }
  506. }
  507. private void OnThyroidClassificationFinishEvaluationNotification(object sender, ThyroidSectionResult thyroidSectionResult)
  508. {
  509. try
  510. {
  511. var elapsedTime = Environment.TickCount - _startTickCount;
  512. if (thyroidSectionResult != null)
  513. {
  514. Logger.Info("Finish AI Detection");
  515. var labelName = "";
  516. var confidence = thyroidSectionResult.Score.ToString("0.0" + "%");
  517. switch (thyroidSectionResult.ThyroidSectionType)
  518. {
  519. case EnumThyroidSectionType.Null:
  520. labelName = "其他切面";
  521. break;
  522. case EnumThyroidSectionType.LeftCrossSection:
  523. labelName = "左侧甲状腺横切切面";
  524. break;
  525. case EnumThyroidSectionType.RightCrossSection:
  526. labelName = "右侧甲状腺横切切面";
  527. break;
  528. case EnumThyroidSectionType.LongitudinalSection:
  529. labelName = "甲状腺纵切切面";
  530. break;
  531. case EnumThyroidSectionType.IsthmusSection:
  532. labelName = "甲状腺峡部切面";
  533. break;
  534. }
  535. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  536. {
  537. ResultInfoText.Text = $"{labelName}\r\n置信度:{confidence}";
  538. ElapsedTimeText.Text = $"AI耗时: {elapsedTime}ms";
  539. }));
  540. }
  541. else
  542. {
  543. Logger.Info("diag Result is null!");
  544. }
  545. }
  546. catch
  547. { }
  548. }
  549. private void OnMyocardialFinishEvaluation(object sender, DetectedObject diagResult)
  550. {
  551. try
  552. {
  553. _currentDetectedObject = diagResult;
  554. if (diagResult != null)
  555. {
  556. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Finish AI Detection");
  557. var elapsedTime = Environment.TickCount - _startTickCount;
  558. UpdateTransforms();
  559. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Update Transforms");
  560. // 删掉旧的Roi和Organ
  561. RemoveRois();
  562. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Remove Rois");
  563. RemoveOrgans();
  564. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Remove Ograns");
  565. var roiList = new List<Roi>();
  566. if (diagResult.Contours != null && diagResult.Contours.Count() > 0)
  567. {
  568. var bondingBox = new Infrastucture.MyRect(diagResult.BoundingBox.Left, diagResult.BoundingBox.Top, diagResult.BoundingBox.Width, diagResult.BoundingBox.Height);
  569. var roi = new Roi(EnumOrgans.Null, bondingBox, diagResult.Contours, System.Windows.Media.Brushes.Green, string.Empty, diagResult.Confidence.ToString("0.0" + "%"), null);
  570. roiList.Add(roi);
  571. }
  572. _rois = roiList;
  573. // 更新画布上显示的Roi和Organ
  574. UpdateRois();
  575. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Update Rois");
  576. if (SettingConfig.Instance.IsShowOrgansContour)
  577. {
  578. UpdateOrgans();
  579. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Update Organs");
  580. }
  581. var priorityScore = diagResult.Confidence;
  582. // 更新显示在侧面的诊断详情
  583. string strResult = ResultInfoToString(priorityScore);
  584. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  585. {
  586. ResultInfoText.Text = strResult;
  587. ElapsedTimeText.Text = $"AI耗时: {elapsedTime}ms";
  588. }));
  589. }
  590. else
  591. {
  592. Logger.Info("diag Result is null!");
  593. }
  594. }
  595. catch
  596. { }
  597. }
  598. private void StopDiagnosis()
  599. {
  600. if (_diagnosis != null)
  601. {
  602. _diagnosis.StartEvaluation -= OnStartEvaluation;
  603. _diagnosis.FinishEvaluation -= OnFinishEvaluation;
  604. _diagnosis.NotifyError -= OnNotifyError;
  605. _diagnosis.Stop();
  606. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Stop Diagnosis");
  607. }
  608. if (_myocardialDiagnosis != null)
  609. {
  610. _myocardialDiagnosis.NotifyError -= OnNotifyError;
  611. _myocardialDiagnosis.StartEvaluation -= OnStartEvaluation;
  612. _myocardialDiagnosis.FinishEvaluation -= OnMyocardialFinishEvaluation;
  613. _myocardialDiagnosis.NotifyLog -= OnNotifyLog;
  614. _myocardialDiagnosis.Stop();
  615. _myocardialDiagnosis = null;
  616. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Close Diagnosis");
  617. }
  618. if (_thyroidClassification != null)
  619. {
  620. _thyroidClassification.StartEvaluation -= OnStartEvaluation;
  621. _thyroidClassification.NotifyError -= OnNotifyError;
  622. _thyroidClassification.FinishEvaluation -= OnThyroidClassificationFinishEvaluationNotification;
  623. _thyroidClassification.Close();
  624. _thyroidClassification = null;
  625. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Close ThyroidClassificaion");
  626. }
  627. }
  628. private void OnPlayClick(object sender, RoutedEventArgs e)
  629. {
  630. if (_player != null)
  631. {
  632. if (_myocardialDiagnosis != null)
  633. {
  634. ExtractContoursBtn.IsChecked = false;
  635. }
  636. _player.Continue();
  637. _isPlaying = true;
  638. PlayButton.Visibility = Visibility.Collapsed;
  639. PauseButton.Visibility = Visibility.Visible;
  640. }
  641. }
  642. private void OnPauseClick(object sender, RoutedEventArgs e)
  643. {
  644. if (_player != null)
  645. {
  646. _player.Pause();
  647. _isPlaying = false;
  648. PlayButton.Visibility = Visibility.Visible;
  649. PauseButton.Visibility = Visibility.Collapsed;
  650. DetectImage();
  651. }
  652. }
  653. private void OnValueChanged(object sender, List<SettingProperty> e)
  654. {
  655. if (e.Contains(SettingProperty.CompleteMyocardialImg))
  656. {
  657. if (_myocardialDiagnosis != null)
  658. {
  659. _myocardialDiagnosis.CompleteMyocardialImg = SettingConfig.Instance.CompleteMyocardialImg;
  660. }
  661. }
  662. if (e.Contains(SettingProperty.IsSimulation) || e.Contains(SettingProperty.RAMUsed) || e.Contains(SettingProperty.CPUUsed))//当模拟占用功能变更
  663. {
  664. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} IsSimulation:\"{SettingConfig.Instance.IsSimulation}\",CPU Used:\"{SettingConfig.Instance.CPUUsed}\",RAM Used:\"{SettingConfig.Instance.RAMUsed}\"");
  665. RefreshUsedStatus();
  666. }
  667. //当AI功能变更
  668. if (e.Contains(SettingProperty.Performance) || e.Contains(SettingProperty.IsEnableAI) || e.Contains(SettingProperty.AIDiagnosisType))
  669. {
  670. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Enable AI:\"{SettingConfig.Instance.IsEnableAI}\",AI Performance:\"{SettingConfig.Instance.Performance}\",Detect Mode:\"{SettingConfig.Instance.DetectMode}\",Is Cropped:\"{!SettingConfig.Instance.CropImage}\",Detect Tps:\"{SettingConfig.Instance.DetectTps}\",Interval Time:\"{SettingConfig.Instance.IntervalTime}\"");
  671. CloseDiagnosis();
  672. CleanAIResult();
  673. if (SettingConfig.Instance.IsEnableAI)
  674. {
  675. StartDiagnosis();
  676. if (SettingConfig.Instance.IsVideo == false)//当源文件为图片的情况下,就重新Show一次给AI提供图片信息。
  677. {
  678. DetectImage();
  679. }
  680. }
  681. }
  682. else
  683. {
  684. if (SettingConfig.Instance.IsEnableAI)
  685. {
  686. if (e.Contains(SettingProperty.CropImage))
  687. {
  688. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Is Cropped:\"{!SettingConfig.Instance.CropImage}\"");
  689. if (_diagnosis != null)
  690. {
  691. _diagnosis.IsCropped = !SettingConfig.Instance.CropImage;
  692. }
  693. }
  694. if (e.Contains(SettingProperty.DetectTps))
  695. {
  696. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Detect Tps:\"{SettingConfig.Instance.DetectTps}\"");
  697. if (_diagnosis != null)
  698. {
  699. _diagnosis.DetectTps = SettingConfig.Instance.DetectTps;
  700. }
  701. if (_myocardialDiagnosis != null)
  702. {
  703. _myocardialDiagnosis.DetectTps = SettingConfig.Instance.DetectTps;
  704. }
  705. if (_thyroidClassification != null)
  706. {
  707. _thyroidClassification.DetectTps = SettingConfig.Instance.DetectTps;
  708. }
  709. }
  710. if (e.Contains(SettingProperty.IntervalTime))
  711. {
  712. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Interval Time:\"{SettingConfig.Instance.IntervalTime}\"");
  713. if (_diagnosis != null)
  714. {
  715. _diagnosis.IntervalTime = SettingConfig.Instance.IntervalTime;
  716. }
  717. if (_myocardialDiagnosis != null)
  718. {
  719. _myocardialDiagnosis.IntervalTime = SettingConfig.Instance.IntervalTime;
  720. }
  721. if (_thyroidClassification != null)
  722. {
  723. _thyroidClassification.IntervalTime = SettingConfig.Instance.IntervalTime;
  724. }
  725. }
  726. if (e.Contains(SettingProperty.DetectMode))
  727. {
  728. Logger.Info($"Detect Mode:\"{SettingConfig.Instance.DetectMode}\"");
  729. if (_diagnosis != null)
  730. {
  731. _diagnosis.DetectMode = SettingConfig.Instance.DetectMode;
  732. }
  733. if (_myocardialDiagnosis != null)
  734. {
  735. _myocardialDiagnosis.DetectMode = (EnumDetectMode)SettingConfig.Instance.DetectMode;
  736. }
  737. if (_thyroidClassification != null)
  738. {
  739. _thyroidClassification.DetectMode = SettingConfig.Instance.DetectMode;
  740. }
  741. }
  742. }
  743. }
  744. if (e.Contains(SettingProperty.IsShowOrgansContour))
  745. {
  746. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Is Show Organs Contour:\"{SettingConfig.Instance.IsShowOrgansContour}\"");
  747. if (SettingConfig.Instance.IsShowOrgansContour)
  748. {
  749. UpdateOrgans();
  750. }
  751. else
  752. {
  753. RemoveOrgans();
  754. }
  755. }
  756. if (e.Contains(SettingProperty.DisplayType))
  757. {
  758. Logger.Info($"Thread Id: {Thread.CurrentThread.ManagedThreadId} Display Type:\"{SettingConfig.Instance.DisplayType}\"");
  759. if (SettingConfig.Instance.DisplayType == EnumDisplayType.Border)
  760. {
  761. if (_diagnosis != null)
  762. {
  763. _diagnosis.EnableLesionDescription = false;
  764. _diagnosis.EnableOrganDescription = false;
  765. _diagnosis.EnableLesionSeg = false;
  766. }
  767. }
  768. else
  769. {
  770. if (_diagnosis != null)
  771. {
  772. _diagnosis.EnableLesionDescription = true;
  773. _diagnosis.EnableOrganDescription = true;
  774. _diagnosis.EnableLesionSeg = true;
  775. }
  776. }
  777. UpdateRois();
  778. }
  779. if (e.Contains(SettingProperty.IsCycleImagesPlay))
  780. {
  781. if (SettingConfig.Instance.IsCycleImagesPlay)//当循环图片播放未开启
  782. {
  783. var imagesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestImages");
  784. if (Directory.Exists(imagesPath))
  785. {
  786. string[] images = Directory.GetFiles(imagesPath);
  787. _cycleImagesList = new List<string>();
  788. foreach (string image in images)
  789. {
  790. if (image.EndsWith(".jpg") || image.EndsWith(".bmp") || image.EndsWith(".png") || image.EndsWith(".jpeg"))
  791. {
  792. _cycleImagesList.Add(image);
  793. }
  794. }
  795. if (_cycleImagesList.Count == 0)
  796. {
  797. Dispatcher.Invoke(() =>
  798. {
  799. MessageBox.Show($"Cycle Image Test Failed.The List is empty. Please check.");
  800. Close();
  801. });
  802. }
  803. StartCycleImagesTest();
  804. }
  805. else
  806. {
  807. Dispatcher.Invoke(() =>
  808. {
  809. MessageBox.Show($"TestImages file missed. The path is {imagesPath}. Please check.");
  810. Close();
  811. });
  812. }
  813. }
  814. }
  815. }
  816. private void StartCycleImagesTest()
  817. {
  818. if (_cycleTestThread == null || !_cycleTestThread.IsAlive)
  819. {
  820. _cycleTestThread = new Thread(() => DoCycleImagesTest())
  821. {
  822. IsBackground = true,
  823. Name = "CycleImageTest"
  824. };
  825. _cycleTestThread.Start();
  826. }
  827. }
  828. private void DoCycleImagesTest()
  829. {
  830. while (true)
  831. {
  832. foreach (var image in _cycleImagesList)
  833. {
  834. Thread.Sleep(SettingConfig.Instance.IntervalTime);
  835. SettingConfig.Instance.UltrasoundImageSourceType = Sourcetype.PictureOrVideoFile;
  836. SettingConfig.Instance.UltrasoundImageSource = image;
  837. SettingConfig.Instance.RaiseSavedEvent(new List<SettingProperty> { SettingProperty.UltrasoundImageSourceType, SettingProperty.UltrasoundImageSource });
  838. }
  839. }
  840. }
  841. private void StartCPUUsed()
  842. {
  843. _cpuUsed = SettingConfig.Instance.CPUUsed;
  844. if (SettingConfig.Instance.CPUUsed == 0)
  845. {
  846. return;
  847. }
  848. for (int i = 0; i < Environment.ProcessorCount; i++)
  849. {
  850. var cpuThread = new Thread(() =>
  851. {
  852. try
  853. {
  854. Stopwatch watch = new Stopwatch();
  855. watch.Start();
  856. while (true)
  857. {
  858. //Make the loop go on for "percentage" milliseconds then sleep the
  859. //remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms.
  860. if (watch.ElapsedMilliseconds > SettingConfig.Instance.CPUUsed)
  861. {
  862. Thread.Sleep(100 - SettingConfig.Instance.CPUUsed);
  863. watch.Reset();
  864. watch.Start();
  865. }
  866. }
  867. }
  868. catch
  869. {
  870. }
  871. })
  872. {
  873. Name = "CPUUsedThread" + i
  874. }
  875. ;
  876. cpuThread.Start();
  877. _cpuThreads.Add(cpuThread);
  878. }
  879. }
  880. private void StopCPUUsed()
  881. {
  882. var oldThread = _cpuThreads.ToList();
  883. Thread.Sleep(100 - SettingConfig.Instance.CPUUsed);
  884. foreach (var t in oldThread)
  885. {
  886. try
  887. {
  888. t.Abort();
  889. }
  890. catch
  891. {
  892. }
  893. }
  894. _cpuUsed = 0;
  895. }
  896. private void StopRAMUsed()
  897. {
  898. if (_ramThread != null && !_ramThread.IsCompleted)
  899. {
  900. Task.WaitAll(_ramThread);
  901. }
  902. _ramUsedList = null;
  903. System.GC.Collect();
  904. System.GC.WaitForPendingFinalizers();
  905. _ramUsed = 0;
  906. }
  907. private void StartRAMUsed()
  908. {
  909. _ramThread = new Task(() =>
  910. {
  911. _ramUsed = SettingConfig.Instance.RAMUsed;
  912. _ramUsedList = new List<Array>();
  913. var ramCoefficient = _ramSize / 16;//只有当内存为16GB的时候,内存系数为1,否则内存系数按比例变化。
  914. int ramListCount;
  915. switch (SettingConfig.Instance.RAMUsed / 10)
  916. {
  917. case 0:
  918. return;
  919. case 1:
  920. ramListCount = 5;
  921. break;
  922. case 2:
  923. ramListCount = 10;
  924. break;
  925. case 3:
  926. ramListCount = 15;
  927. break;
  928. case 4:
  929. ramListCount = 20;
  930. break;
  931. case 5:
  932. ramListCount = 25;
  933. break;
  934. case 6:
  935. ramListCount = 30;
  936. break;
  937. case 7:
  938. ramListCount = 35;
  939. break;
  940. case 8:
  941. ramListCount = 40;
  942. break;
  943. case 9:
  944. ramListCount = 45;
  945. break;
  946. default:
  947. throw new Exception($"RAM Used Failed. RAMUsed value is {SettingConfig.Instance.RAMUsed}");
  948. }
  949. for (int ramlist = 0; ramlist < ramListCount; ramlist++)
  950. {
  951. int[] ramUsedArray = new int[(int)(82000000 * ramCoefficient)];//内存系数为1时,约占用320MB的内存,约为16G的百分之2
  952. for (int i = 0; i < ramUsedArray.Length; i++)
  953. {
  954. ramUsedArray[i] = i;
  955. }
  956. _ramUsedList.Add(ramUsedArray);
  957. ramUsedArray = null;
  958. }
  959. });
  960. _ramThread.Start();
  961. }
  962. private void StopPlay()
  963. {
  964. if (_player != null)
  965. {
  966. _player.InputFrameReceived -= OnInputFrameReceived;
  967. _player.FPSChanged -= OnFPSChanged;
  968. _player.Stop();
  969. }
  970. _isPlaying = false;
  971. PlayButton.IsEnabled = false;
  972. PlayButton.Content = "暂停播放";
  973. UsImage.Source = null;
  974. FPSText.Text = "";
  975. }
  976. private void CleanAIResult()
  977. {
  978. Dispatcher.Invoke(() =>
  979. {
  980. RemoveOrgans();
  981. RemoveRois();
  982. ResultInfoText.Text = "";
  983. ElapsedTimeText.Text = "";
  984. });
  985. _rois = null;
  986. _conclusions = null;
  987. _organs = null;
  988. }
  989. private void OnInputFrameReceived(object sender, Bitmap e)
  990. {
  991. _image = e.Clone(new Rectangle(0, 0, e.Width, e.Height), e.PixelFormat);
  992. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  993. {
  994. var bitmapimage = BitmapHelper.BitmapToBitmapImage(e);
  995. UsImage.Source = bitmapimage;
  996. }));
  997. }
  998. private void OnFPSChanged(object sender, int fps)
  999. {
  1000. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  1001. {
  1002. if (fps > 0)
  1003. {
  1004. FPSText.Text = $"实际帧率:{fps} fps";
  1005. }
  1006. else
  1007. {
  1008. FPSText.Text = "";
  1009. }
  1010. }));
  1011. }
  1012. private void OnFinishEvaluation(object sender, AIDiagResultPerImg diagResult)
  1013. {
  1014. try
  1015. {
  1016. var organString = "";
  1017. if (diagResult != null)
  1018. {
  1019. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Finish AI Detection");
  1020. var elapsedTime = Environment.TickCount - _startTickCount;
  1021. // 整理诊断结果中相关信息
  1022. List<Roi> rois = new List<Roi>();
  1023. Dictionary<EnumOrgans, List<string>> conclusions = new Dictionary<EnumOrgans, List<string>>();
  1024. List<Organ> organs = new List<Organ>();
  1025. UpdateTransforms();
  1026. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Update Transforms");
  1027. foreach (var resultsPerOrgan in diagResult.DiagResultsForEachOrgan)
  1028. {
  1029. organString = organString + resultsPerOrgan.Organ.ToString();
  1030. foreach (var detectedObject in resultsPerOrgan.DetectedObjects)
  1031. {
  1032. bool hasConclusion = true;
  1033. bool hasRoi = false;
  1034. string labelName = string.Empty;
  1035. System.Windows.Media.Brush brush = null;
  1036. string confidence = string.Empty;
  1037. switch (resultsPerOrgan.Organ)
  1038. {
  1039. case EnumOrgans.Breast:
  1040. switch (detectedObject.Label)
  1041. {
  1042. case 0:
  1043. labelName = "未见明显异常";
  1044. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1045. break;
  1046. case 1:
  1047. labelName = "脂肪瘤";
  1048. brush = System.Windows.Media.Brushes.Orange;
  1049. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1050. hasRoi = true;
  1051. break;
  1052. case 2:
  1053. labelName = "BIRads2";
  1054. brush = System.Windows.Media.Brushes.Orange;
  1055. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1056. hasRoi = true;
  1057. break;
  1058. case 3:
  1059. labelName = "BIRads3";
  1060. brush = System.Windows.Media.Brushes.Orange;
  1061. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1062. hasRoi = true;
  1063. break;
  1064. case 4:
  1065. labelName = "BIRads4a";
  1066. brush = System.Windows.Media.Brushes.Red;
  1067. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1068. hasRoi = true;
  1069. break;
  1070. case 5:
  1071. labelName = "BIRads4b";
  1072. brush = System.Windows.Media.Brushes.Red;
  1073. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1074. hasRoi = true;
  1075. break;
  1076. case 6:
  1077. labelName = "BIRads4c";
  1078. brush = System.Windows.Media.Brushes.Red;
  1079. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1080. hasRoi = true;
  1081. break;
  1082. case 7:
  1083. labelName = "BIRads5";
  1084. brush = System.Windows.Media.Brushes.Red;
  1085. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1086. hasRoi = true;
  1087. break;
  1088. default:
  1089. hasConclusion = false;
  1090. break;
  1091. }
  1092. break;
  1093. case EnumOrgans.Liver:
  1094. switch (detectedObject.Label)
  1095. {
  1096. case 0:
  1097. labelName = "未见明显异常";
  1098. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1099. break;
  1100. case 1:
  1101. labelName = "肝内强回声灶";
  1102. brush = System.Windows.Media.Brushes.Orange;
  1103. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1104. hasRoi = true;
  1105. break;
  1106. case 2:
  1107. labelName = "肝血管瘤";
  1108. brush = System.Windows.Media.Brushes.Orange;
  1109. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1110. hasRoi = true;
  1111. break;
  1112. case 3:
  1113. labelName = "肝囊肿";
  1114. brush = System.Windows.Media.Brushes.Orange;
  1115. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1116. hasRoi = true;
  1117. break;
  1118. case 4:
  1119. labelName = "肝癌可能";
  1120. brush = System.Windows.Media.Brushes.Red;
  1121. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1122. hasRoi = true;
  1123. break;
  1124. case 5:
  1125. labelName = "脂肪肝";
  1126. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1127. break;
  1128. case 6:
  1129. labelName = "肝脏弥漫性病变";
  1130. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1131. break;
  1132. case 7:
  1133. labelName = "肝硬化";
  1134. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1135. break;
  1136. case 8:
  1137. labelName = "多囊肝";
  1138. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1139. break;
  1140. default:
  1141. hasConclusion = false;
  1142. break;
  1143. }
  1144. break;
  1145. case EnumOrgans.GallBladder:
  1146. switch (detectedObject.Label)
  1147. {
  1148. case 0:
  1149. labelName = "未见明显异常";
  1150. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1151. break;
  1152. case 1:
  1153. labelName = "胆囊息肉";
  1154. brush = System.Windows.Media.Brushes.Orange;
  1155. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1156. hasRoi = true;
  1157. break;
  1158. case 2:
  1159. labelName = "胆囊结石";
  1160. brush = System.Windows.Media.Brushes.Orange;
  1161. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1162. hasRoi = true;
  1163. break;
  1164. case 3:
  1165. labelName = "胆囊泥沙样结石";
  1166. brush = System.Windows.Media.Brushes.Orange;
  1167. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1168. hasRoi = true;
  1169. break;
  1170. case 4:
  1171. labelName = "胆汁存在异常";
  1172. brush = System.Windows.Media.Brushes.Red;
  1173. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1174. hasRoi = true;
  1175. break;
  1176. case 5:
  1177. labelName = "胆囊壁增厚增粗";
  1178. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1179. break;
  1180. case 6:
  1181. labelName = "腺肌病";
  1182. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1183. break;
  1184. default:
  1185. hasConclusion = false;
  1186. break;
  1187. }
  1188. break;
  1189. case EnumOrgans.Thyroid:
  1190. switch (detectedObject.Label)
  1191. {
  1192. case 0:
  1193. labelName = "未见明显异常";
  1194. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1195. break;
  1196. case 1:
  1197. labelName = "TIRADS 2";
  1198. brush = System.Windows.Media.Brushes.Orange;
  1199. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1200. hasRoi = true;
  1201. break;
  1202. case 2:
  1203. labelName = "TIRADS 3";
  1204. brush = System.Windows.Media.Brushes.Orange;
  1205. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1206. hasRoi = true;
  1207. break;
  1208. case 3:
  1209. labelName = "TIRADS 4a";
  1210. brush = System.Windows.Media.Brushes.Red;
  1211. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1212. hasRoi = true;
  1213. break;
  1214. case 4:
  1215. labelName = "TIRADS 4b";
  1216. brush = System.Windows.Media.Brushes.Red;
  1217. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1218. hasRoi = true;
  1219. break;
  1220. case 5:
  1221. labelName = "TIRADS 4c";
  1222. brush = System.Windows.Media.Brushes.Red;
  1223. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1224. hasRoi = true;
  1225. break;
  1226. case 6:
  1227. labelName = "TIRADS 5";
  1228. brush = System.Windows.Media.Brushes.Red;
  1229. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1230. hasRoi = true;
  1231. break;
  1232. case 7:
  1233. labelName = "存在弥漫性疾病";
  1234. brush = System.Windows.Media.Brushes.Orange;
  1235. confidence = detectedObject.Confidence.ToString("0.0" + "%");
  1236. hasRoi = true;
  1237. break;
  1238. default:
  1239. hasConclusion = false;
  1240. break;
  1241. }
  1242. break;
  1243. default:
  1244. hasConclusion = false;
  1245. break;
  1246. }
  1247. if (hasConclusion)
  1248. {
  1249. if (hasRoi)
  1250. {
  1251. var bondingBox = new MyRect(detectedObject.BoundingBox.Left, detectedObject.BoundingBox.Top, detectedObject.BoundingBox.Width, detectedObject.BoundingBox.Height);
  1252. var roi = new Roi(resultsPerOrgan.Organ, bondingBox, detectedObject.Contours, brush, labelName, confidence, detectedObject.Descriptions.ToList());
  1253. rois.Add(roi);
  1254. }
  1255. else
  1256. {
  1257. if (!conclusions.ContainsKey(resultsPerOrgan.Organ))
  1258. {
  1259. conclusions.Add(resultsPerOrgan.Organ, new List<string>());
  1260. }
  1261. conclusions[resultsPerOrgan.Organ].Add(labelName + "," + detectedObject.Confidence.ToString("0.0" + " % "));//结论,置信度
  1262. }
  1263. }
  1264. }
  1265. var organBondingBox = new MyRect(resultsPerOrgan.OrganBoundBox.Left, resultsPerOrgan.OrganBoundBox.Right, resultsPerOrgan.OrganBoundBox.Width, resultsPerOrgan.OrganBoundBox.Height);
  1266. //var organContor = resultsPerOrgan.OrganContours[0].Select(c => new Infrastucture.MyPoint(c.X, c.Y)).ToArray();
  1267. organs.Add(new Organ(resultsPerOrgan.Organ.ToString(), organBondingBox, resultsPerOrgan.OrganContours));
  1268. }
  1269. // 删掉旧的Roi和Organ
  1270. RemoveRois();
  1271. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Remove Rois");
  1272. RemoveOrgans();
  1273. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Remove Ograns");
  1274. // 设置
  1275. _rois = rois;
  1276. _conclusions = conclusions;
  1277. _organs = organs;
  1278. // 更新画布上显示的Roi和Organ
  1279. UpdateRois();
  1280. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Update Rois");
  1281. if (SettingConfig.Instance.IsShowOrgansContour)
  1282. {
  1283. UpdateOrgans();
  1284. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Update Organs");
  1285. }
  1286. var priorityScore = diagResult.PriorityScore;
  1287. // 更新显示在侧面的诊断详情
  1288. string strResult = ResultInfoToString(priorityScore);
  1289. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  1290. {
  1291. ResultInfoText.Text = $"Organ:{organString}\r\n" + strResult;
  1292. ElapsedTimeText.Text = $"AI耗时: {elapsedTime}ms";
  1293. }));
  1294. }
  1295. else
  1296. {
  1297. Logger.Info("diag Result is null!");
  1298. }
  1299. }
  1300. catch
  1301. { }
  1302. }
  1303. private string ResultInfoToString(float priorityScore)
  1304. {
  1305. string results = $"Priority Score: {priorityScore}";
  1306. Dictionary<EnumOrgans, string> resultPerOrgan = new Dictionary<EnumOrgans, string>();
  1307. // 取出结论
  1308. if (_conclusions != null)
  1309. {
  1310. foreach (var organ in _conclusions.Keys)
  1311. {
  1312. if (!resultPerOrgan.ContainsKey(organ))
  1313. {
  1314. resultPerOrgan.Add(organ, string.Empty);
  1315. }
  1316. foreach (var conclusion in _conclusions[organ])
  1317. {
  1318. string existed = resultPerOrgan[organ];
  1319. if (existed.Length != 0)
  1320. {
  1321. existed += "\r\n";
  1322. }
  1323. var arrConclusion = conclusion.Split(',');
  1324. var strConclusion = arrConclusion[0];
  1325. var strconfidence = arrConclusion[1];
  1326. existed += $"{organ}: {strConclusion}\r\n";
  1327. existed += $"置信度: {strconfidence}\r\n";
  1328. resultPerOrgan[organ] = existed;
  1329. }
  1330. }
  1331. }
  1332. // 取出roi的描述
  1333. if (_rois != null)
  1334. {
  1335. for (int ni = 0; ni < _rois.Count; ni++)
  1336. {
  1337. var roi = _rois[ni];
  1338. if (!resultPerOrgan.ContainsKey(roi.Organ))
  1339. {
  1340. resultPerOrgan.Add(roi.Organ, string.Empty);
  1341. }
  1342. string existed = resultPerOrgan[roi.Organ];
  1343. if (existed.Length != 0)
  1344. {
  1345. existed += "\r\n";
  1346. }
  1347. string newroi = "病灶 " + ni + ":\r\n";
  1348. newroi += $"{roi.Organ}: {roi.LabelName}\r\n";
  1349. newroi += $"置信度: {roi.Confidence}\r\n";
  1350. if (roi.Descriptions != null)
  1351. {
  1352. newroi += DescriptionsToString(roi.Descriptions);
  1353. }
  1354. existed += newroi;
  1355. resultPerOrgan[roi.Organ] = existed;
  1356. }
  1357. }
  1358. // 合到一起
  1359. foreach (var organ in resultPerOrgan.Keys)
  1360. {
  1361. if (results.Length != 0)
  1362. {
  1363. results += "\r\n";
  1364. }
  1365. results += resultPerOrgan[organ];
  1366. }
  1367. return results;
  1368. }
  1369. private string DescriptionsToString(List<IDescription> descriptions)
  1370. {
  1371. string strDescription = string.Empty;
  1372. var lesionSize = (DescriptionLesionSize)descriptions.Find(x => x.Type == EnumDescriptionType.LesionSize);
  1373. if (lesionSize != null)
  1374. {
  1375. string strSize = string.Empty;
  1376. if (lesionSize.Value.HorizontalLengthInPixel > lesionSize.Value.VerticalLengthInPixel)
  1377. {
  1378. strSize = "<1";
  1379. }
  1380. else
  1381. {
  1382. strSize = ">=1";
  1383. }
  1384. strDescription += "纵横比:" + strSize + "\r\n";
  1385. }
  1386. var shape = (DescriptionShape)descriptions.Find(x => x.Type == EnumDescriptionType.Shape);
  1387. if (shape != null)
  1388. {
  1389. string strShape = string.Empty;
  1390. switch (shape.Value)
  1391. {
  1392. case EnumDesShapeValue.Oval:
  1393. strShape = "椭圆形";
  1394. break;
  1395. case EnumDesShapeValue.Round:
  1396. strShape = "圆形";
  1397. break;
  1398. case EnumDesShapeValue.Irregular:
  1399. strShape = "不规则";
  1400. break;
  1401. }
  1402. strDescription += "形状:" + strShape + "\r\n";
  1403. }
  1404. var orientation = (DescriptionOrientation)descriptions.Find(x => x.Type == EnumDescriptionType.Orientation);
  1405. if (orientation != null)
  1406. {
  1407. string strOrientation = string.Empty;
  1408. switch (orientation.Value)
  1409. {
  1410. case EnumDesOrientationValue.Parallel:
  1411. strOrientation = "平行";
  1412. break;
  1413. case EnumDesOrientationValue.NonParallel:
  1414. strOrientation = "非平行";
  1415. break;
  1416. }
  1417. strDescription += "方向:" + strOrientation + "\r\n";
  1418. var echo = (DescriptionEchoPattern)descriptions.Find(x => x.Type == EnumDescriptionType.EchoPattern);
  1419. if (echo != null)
  1420. {
  1421. string strEcho = string.Empty;
  1422. switch (echo.Value)
  1423. {
  1424. case EnumDesEchoPatternValue.Anechoic:
  1425. strEcho = "无回声";
  1426. break;
  1427. case EnumDesEchoPatternValue.Hypoechoic:
  1428. strEcho = "低回声";
  1429. break;
  1430. case EnumDesEchoPatternValue.Hyperechoic:
  1431. strEcho = "高回声";
  1432. break;
  1433. case EnumDesEchoPatternValue.Strongechoic:
  1434. strEcho = "强回声";
  1435. break;
  1436. case EnumDesEchoPatternValue.Complex:
  1437. strEcho = "混合回声";
  1438. break;
  1439. case EnumDesEchoPatternValue.Isoechoic:
  1440. strEcho = "等回声";
  1441. break;
  1442. }
  1443. strDescription += "回声类型:" + strEcho + "\r\n";
  1444. }
  1445. var bound = (DescriptionLesionBoundary)descriptions.Find(x => x.Type == EnumDescriptionType.LesionBoundary);
  1446. if (bound != null)
  1447. {
  1448. string strBound = string.Empty;
  1449. switch (bound.Value)
  1450. {
  1451. case EnumDesLesionBoundaryValue.AbruptInterface:
  1452. strBound = "清晰";
  1453. break;
  1454. case EnumDesLesionBoundaryValue.EchogenicHalo:
  1455. strBound = "模糊";
  1456. break;
  1457. }
  1458. strDescription += "边界:" + strBound + "\r\n";
  1459. }
  1460. var margin = (DescriptionMargin)descriptions.Find(x => x.Type == EnumDescriptionType.Margin);
  1461. if (margin != null)
  1462. {
  1463. string strMargin = string.Empty;
  1464. switch (margin.Value)
  1465. {
  1466. case EnumDesMarginValue.Circumscribed:
  1467. strMargin = "光整";
  1468. break;
  1469. case EnumDesMarginValue.NonCircumscribed:
  1470. strMargin = "不光整";
  1471. break;
  1472. }
  1473. strDescription += "边缘:" + strMargin + "\r\n";
  1474. }
  1475. }
  1476. var calcifications = (DescriptionCalcifications)descriptions.Find(x => x.Type == EnumDescriptionType.Calcifications);
  1477. if (calcifications != null)
  1478. {
  1479. string strCalcifications = string.Empty;
  1480. switch (calcifications.Value)
  1481. {
  1482. case EnumCalcificationsValue.NoCalcifications:
  1483. strCalcifications = "无钙化";
  1484. break;
  1485. case EnumCalcificationsValue.Macrocalcifications:
  1486. strCalcifications = "粗钙化";
  1487. break;
  1488. case EnumCalcificationsValue.Microcalcifications:
  1489. strCalcifications = "微钙化";
  1490. break;
  1491. }
  1492. strDescription += "钙化:" + strCalcifications + "\r\n";
  1493. }
  1494. var thyroidMargin = (DescriptionThyroidMargin)descriptions.Find(x => x.Type == EnumDescriptionType.ThyroidMargin);
  1495. if (thyroidMargin != null)
  1496. {
  1497. string strMargin = string.Empty;
  1498. switch (thyroidMargin.Value)
  1499. {
  1500. case EnumDesThyroidMarginValue.Smooth:
  1501. strMargin = "光滑";
  1502. break;
  1503. case EnumDesThyroidMarginValue.IllDefined:
  1504. strMargin = "不清晰";
  1505. break;
  1506. case EnumDesThyroidMarginValue.Lobulated:
  1507. strMargin = "分叶";
  1508. break;
  1509. case EnumDesThyroidMarginValue.Irregular:
  1510. strMargin = "不规则";
  1511. break;
  1512. case EnumDesThyroidMarginValue.ExtraThyroidalExtension:
  1513. strMargin = "甲状腺外扩";
  1514. break;
  1515. }
  1516. strDescription += "边缘:" + strMargin + "\r\n";
  1517. }
  1518. var thyroidShape = (DescriptionThyroidShape)descriptions.Find(x => x.Type == EnumDescriptionType.ThyroidShape);
  1519. if (thyroidShape != null)
  1520. {
  1521. string strShape = string.Empty;
  1522. switch (thyroidShape.Value)
  1523. {
  1524. case EnumDesThyroidShapeValue.WiderThanTall:
  1525. strShape = "水平位";
  1526. break;
  1527. case EnumDesThyroidShapeValue.TallThanWider:
  1528. strShape = "垂直位";
  1529. break;
  1530. }
  1531. strDescription += "形状:" + strShape + "\r\n";
  1532. }
  1533. var thyroidEchogenicFoci = (DescriptionThyroidEchogenicFoci)descriptions.Find(x => x.Type == EnumDescriptionType.ThyroidEchogenicFoci);
  1534. if (thyroidEchogenicFoci != null)
  1535. {
  1536. string strEchogenicFoci = string.Empty;
  1537. switch (thyroidEchogenicFoci.Value)
  1538. {
  1539. case EnumDesThyroidEchogenicFociValue.NoCifications:
  1540. strEchogenicFoci = "无钙化";
  1541. break;
  1542. case EnumDesThyroidEchogenicFociValue.Coarsecalcifications:
  1543. strEchogenicFoci = "粗钙化";
  1544. break;
  1545. case EnumDesThyroidEchogenicFociValue.Microcalcifications:
  1546. strEchogenicFoci = "微钙化";
  1547. break;
  1548. }
  1549. strDescription += "局灶性强回声:" + strEchogenicFoci + "\r\n";
  1550. }
  1551. var thyroidEchoPattern = (DescriptionThyroidEchoPattern)descriptions.Find(x => x.Type == EnumDescriptionType.ThyroidEchoPattern);
  1552. if (thyroidEchoPattern != null)
  1553. {
  1554. string strEcho = string.Empty;
  1555. switch (thyroidEchoPattern.Value)
  1556. {
  1557. case EnumDesThyroidEchoPatternValue.Anechoic:
  1558. strEcho = "无回声";
  1559. break;
  1560. case EnumDesThyroidEchoPatternValue.Hyperechoic:
  1561. strEcho = "高回声";
  1562. break;
  1563. case EnumDesThyroidEchoPatternValue.Isoechoic:
  1564. strEcho = "等回声";
  1565. break;
  1566. case EnumDesThyroidEchoPatternValue.Hypoechoic:
  1567. strEcho = "低回声";
  1568. break;
  1569. case EnumDesThyroidEchoPatternValue.HypoechoicLower:
  1570. strEcho = "极低回声";
  1571. break;
  1572. }
  1573. strDescription += "回声类型:" + strEcho + "\r\n";
  1574. }
  1575. return strDescription;
  1576. }
  1577. private void OnStartEvaluation(object sender, EventArgs e)
  1578. {
  1579. Logger.Info("Thread Id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Start AI Detection");
  1580. _startTickCount = Environment.TickCount;
  1581. Dispatcher.Invoke(() =>
  1582. {
  1583. ErrorInfoText.Text = null;
  1584. });
  1585. }
  1586. private void RemoveRois()
  1587. {
  1588. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  1589. {
  1590. // 移除所有旧的ROI
  1591. if (_rois != null)
  1592. {
  1593. for (int ni = 0; ni < _rois.Count; ni++)
  1594. {
  1595. RemoveRoiInCanvas(ni.ToString(), _rois[ni].Contours.Length);
  1596. }
  1597. }
  1598. }));
  1599. }
  1600. private void RemoveOrgans()
  1601. {
  1602. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  1603. {
  1604. // 移除所有旧的Organ
  1605. if (_organs != null)
  1606. {
  1607. for (int ni = 0; ni < _organs.Count; ni++)
  1608. {
  1609. RemoveOrganInCanvas(_organs[ni]);
  1610. }
  1611. }
  1612. }));
  1613. }
  1614. private void UpdateTransforms()
  1615. {
  1616. if (_image != null)
  1617. {
  1618. // 使图片保持长宽比例,居中显示,需要平移和缩放
  1619. var imgWidth = _image.Width;
  1620. var imgHeight = _image.Height;
  1621. var canvasWidth = UsCanvas.ActualWidth;
  1622. var canvasHeight = UsCanvas.ActualHeight;
  1623. var scaleX = canvasWidth / imgWidth;
  1624. var scaleY = canvasHeight / imgHeight;
  1625. var scale = scaleX < scaleY ? scaleX : scaleY;
  1626. double offsetX, offsetY;
  1627. if (Math.Abs(scale - scaleX) < 0.0001)
  1628. {
  1629. offsetY = 0.5 * (scaleY - scale) * imgHeight;
  1630. offsetX = 0;
  1631. }
  1632. else
  1633. {
  1634. offsetX = 0.5 * (scaleX - scale) * imgWidth;
  1635. offsetY = 0;
  1636. }
  1637. _transform = new MyTransform(scale, offsetX, offsetY);
  1638. }
  1639. }
  1640. private void UpdateRois(bool isLine = false)
  1641. {
  1642. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  1643. {
  1644. if (_rois != null)
  1645. {
  1646. for (int ni = 0; ni < _rois.Count; ni++)
  1647. {
  1648. DrawRoiInCanvas(_rois[ni], ni.ToString(), isLine);
  1649. }
  1650. }
  1651. }));
  1652. }
  1653. private void UpdateOrgans()
  1654. {
  1655. Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  1656. {
  1657. if (_organs != null)
  1658. {
  1659. for (int ni = 0; ni < _organs.Count; ni++)
  1660. {
  1661. DrawOrganInCanvas(_organs[ni]);
  1662. }
  1663. }
  1664. }));
  1665. }
  1666. private void DrawRoiInCanvas(Roi roi, string roiName, bool isLine = false)
  1667. {
  1668. if (_transform == null)
  1669. {
  1670. return;
  1671. }
  1672. // 已有则删除
  1673. RemoveRoiInCanvas(roiName, roi.Contours.Length);
  1674. int contoursLength = roi.Contours.Length;
  1675. if ((!_isPlaying || !SettingConfig.Instance.IsVideo || SettingConfig.Instance.DisplayType == EnumDisplayType.Contour) && contoursLength > 0)//当源图像为视频暂停播放时或者当源图像为图片时或者病灶显示方式为轮廓时,都显示为轮廓,其他情况为画框
  1676. {
  1677. //病灶画轮廓
  1678. for (int ni = 0; ni < contoursLength; ni++)
  1679. {
  1680. Point2D[] contour = roi.Contours[ni];
  1681. PointCollection contourPoints = new PointCollection();
  1682. for (int nj = 0; nj < contour.Length; nj++)
  1683. {
  1684. var point = new System.Windows.Point(contour[nj].X, contour[nj].Y);
  1685. var transPoint = _transform.Transform(point);
  1686. contourPoints.Add(transPoint);
  1687. }
  1688. if (isLine)
  1689. {
  1690. System.Windows.Shapes.Polyline contourDraw = new System.Windows.Shapes.Polyline();
  1691. contourDraw.Points = contourPoints;
  1692. contourDraw.StrokeThickness = 3;
  1693. contourDraw.Stroke = roi.Color;
  1694. contourDraw.StrokeLineJoin = PenLineJoin.Round;
  1695. UsCanvas.Children.Add(contourDraw);
  1696. string contourName = "ROI_Contour_" + roiName + "_" + ni;
  1697. UsCanvas.RegisterName(contourName, contourDraw);
  1698. }
  1699. else
  1700. {
  1701. System.Windows.Shapes.Polygon contourDraw = new System.Windows.Shapes.Polygon();
  1702. contourDraw.Points = contourPoints;
  1703. contourDraw.StrokeThickness = 3;
  1704. contourDraw.Stroke = roi.Color;
  1705. contourDraw.StrokeLineJoin = PenLineJoin.Round;
  1706. UsCanvas.Children.Add(contourDraw);
  1707. string contourName = "ROI_Contour_" + roiName + "_" + ni;
  1708. UsCanvas.RegisterName(contourName, contourDraw);
  1709. }
  1710. }
  1711. // 画横轴纵轴
  1712. if (roi.Descriptions != null)
  1713. {
  1714. var lesionSize = (DescriptionLesionSize)roi.Descriptions.Find(x => x.Type == EnumDescriptionType.LesionSize);
  1715. if (lesionSize != null)
  1716. {
  1717. var pointLineH1 = new System.Windows.Point(lesionSize.Value.HorizontalPoint1.X, lesionSize.Value.HorizontalPoint1.Y);
  1718. var pointLineH2 = new System.Windows.Point(lesionSize.Value.HorizontalPoint2.X, lesionSize.Value.HorizontalPoint2.Y);
  1719. var pointLineV1 = new System.Windows.Point(lesionSize.Value.VerticalPoint1.X, lesionSize.Value.VerticalPoint1.Y);
  1720. var pointLineV2 = new System.Windows.Point(lesionSize.Value.VerticalPoint2.X, lesionSize.Value.VerticalPoint2.Y);
  1721. var transPointH1 = _transform.Transform(pointLineH1);
  1722. var transPointH2 = _transform.Transform(pointLineH2);
  1723. var transPointV1 = _transform.Transform(pointLineV1);
  1724. var transPointV2 = _transform.Transform(pointLineV2);
  1725. System.Windows.Shapes.Line lineH = new System.Windows.Shapes.Line
  1726. {
  1727. StrokeThickness = 1,
  1728. Stroke = roi.Color,
  1729. X1 = transPointH1.X,
  1730. Y1 = transPointH1.Y,
  1731. X2 = transPointH2.X,
  1732. Y2 = transPointH2.Y
  1733. };
  1734. System.Windows.Shapes.Line lineV = new System.Windows.Shapes.Line
  1735. {
  1736. StrokeThickness = 1,
  1737. Stroke = roi.Color,
  1738. X1 = transPointV1.X,
  1739. Y1 = transPointV1.Y,
  1740. X2 = transPointV2.X,
  1741. Y2 = transPointV2.Y
  1742. };
  1743. UsCanvas.Children.Add(lineH);
  1744. string lineHName = "ROI_LineH_" + roiName;
  1745. UsCanvas.RegisterName(lineHName, lineH);
  1746. UsCanvas.Children.Add(lineV);
  1747. string lineVName = "ROI_LineV_" + roiName;
  1748. UsCanvas.RegisterName(lineVName, lineV);
  1749. }
  1750. }
  1751. }
  1752. else
  1753. {
  1754. //病灶画框
  1755. var rect = new System.Windows.Rect(roi.BoundBox.Left, roi.BoundBox.Top, roi.BoundBox.Width, roi.BoundBox.Height);
  1756. var transRect = _transform.Transform(rect);
  1757. System.Windows.Shapes.Rectangle rectDraw = new System.Windows.Shapes.Rectangle();
  1758. rectDraw.StrokeThickness = 3;
  1759. rectDraw.Stroke = roi.Color;
  1760. rectDraw.Width = transRect.Width;
  1761. rectDraw.Height = transRect.Height;
  1762. Canvas.SetLeft(rectDraw, transRect.Left);
  1763. Canvas.SetTop(rectDraw, transRect.Top);
  1764. UsCanvas.Children.Add(rectDraw);
  1765. string rectName = "ROI_Rect_" + roiName;
  1766. UsCanvas.RegisterName(rectName, rectDraw);
  1767. }
  1768. // 将Roi的序号写在左上角
  1769. var pointLT = new System.Windows.Point(roi.BoundBox.Left, roi.BoundBox.Top);
  1770. var transPointLT = _transform.Transform(pointLT);
  1771. var textLeft = transPointLT.X - 16;
  1772. var textTop = transPointLT.Y;
  1773. TextBlock text = new TextBlock
  1774. {
  1775. Text = roiName,
  1776. FontSize = 16,
  1777. FontWeight = System.Windows.FontWeights.Bold,
  1778. Foreground = roi.Color,
  1779. VerticalAlignment = VerticalAlignment.Top
  1780. };
  1781. Canvas.SetLeft(text, textLeft);
  1782. Canvas.SetTop(text, textTop);
  1783. UsCanvas.Children.Add(text);
  1784. string textName = "ROI_Text_" + roiName;
  1785. UsCanvas.RegisterName(textName, text);
  1786. }
  1787. private void DrawOrganInCanvas(Organ organ)
  1788. {
  1789. if (_transform == null)
  1790. {
  1791. return;
  1792. }
  1793. // 已有则删除
  1794. RemoveOrganInCanvas(organ);
  1795. if (organ.Contours == null)
  1796. {
  1797. return;
  1798. }
  1799. // 有轮廓就显示轮廓,没有轮廓就显示方框
  1800. string organName = organ.OrganName;
  1801. if (organ.Contours.Length > 0)
  1802. {
  1803. int count = organ.Contours.Length;
  1804. for (int ni = 0; ni < count; ni++)
  1805. {
  1806. Point2D[] contour = organ.Contours[ni];
  1807. PointCollection contourPoints = new PointCollection();
  1808. for (int nj = 0; nj < contour.Length; nj++)
  1809. {
  1810. var point = new System.Windows.Point(contour[nj].X, contour[nj].Y);
  1811. var transPoint = _transform.Transform(point);
  1812. contourPoints.Add(transPoint);
  1813. }
  1814. System.Windows.Shapes.Polygon contourDraw = new System.Windows.Shapes.Polygon();
  1815. contourDraw.Points = contourPoints;
  1816. contourDraw.StrokeThickness = 3;
  1817. contourDraw.Stroke = organ.Color;
  1818. UsCanvas.Children.Add(contourDraw);
  1819. string contourName = "Organ_Contour_" + organName + "_" + ni;
  1820. UsCanvas.RegisterName(contourName, contourDraw);
  1821. }
  1822. }
  1823. else
  1824. {
  1825. var rect = new System.Windows.Rect(organ.BoundBox.Left, organ.BoundBox.Top, organ.BoundBox.Width, organ.BoundBox.Height);
  1826. var transRect = _transform.Transform(rect);
  1827. System.Windows.Shapes.Rectangle rectDraw = new System.Windows.Shapes.Rectangle
  1828. {
  1829. StrokeThickness = 3,
  1830. Stroke = organ.Color,
  1831. Width = transRect.Width,
  1832. Height = transRect.Height
  1833. };
  1834. Canvas.SetLeft(rectDraw, transRect.Left);
  1835. Canvas.SetTop(rectDraw, transRect.Top);
  1836. UsCanvas.Children.Add(rectDraw);
  1837. string rectName = "Organ_Rect_" + organName;
  1838. UsCanvas.RegisterName(rectName, rectDraw);
  1839. }
  1840. // 将Organ的序号写在左上角
  1841. var pointLT = new System.Windows.Point(organ.BoundBox.Left, organ.BoundBox.Top);
  1842. var transPointLT = _transform.Transform(pointLT);
  1843. var textLeft = transPointLT.X + 16;
  1844. var textTop = transPointLT.Y;
  1845. TextBlock text = new TextBlock
  1846. {
  1847. Text = organName,
  1848. FontSize = 16,
  1849. FontWeight = FontWeights.Bold,
  1850. Foreground = organ.Color,
  1851. VerticalAlignment = VerticalAlignment.Top
  1852. };
  1853. Canvas.SetLeft(text, textLeft);
  1854. Canvas.SetTop(text, textTop);
  1855. UsCanvas.Children.Add(text);
  1856. string textName = "Organ_Text_" + organName;
  1857. UsCanvas.RegisterName(textName, text);
  1858. }
  1859. private void RemoveOrganInCanvas(Organ organ)
  1860. {
  1861. string organName = organ.OrganName;
  1862. // 框
  1863. string rectName = "Organ_Rect_" + organName;
  1864. System.Windows.Shapes.Rectangle rectExist = UsCanvas.FindName(rectName) as System.Windows.Shapes.Rectangle;
  1865. if (rectExist != null)
  1866. {
  1867. UsCanvas.Children.Remove(rectExist);
  1868. UsCanvas.UnregisterName(rectName);
  1869. }
  1870. // 轮廓
  1871. int count = organ.Contours.Length;
  1872. for (int ni = 0; ni < count; ni++)
  1873. {
  1874. string contourName = "Organ_Contour_" + organName + "_" + ni;
  1875. System.Windows.Shapes.Polygon contourExist = UsCanvas.FindName(contourName) as System.Windows.Shapes.Polygon;
  1876. if (contourExist != null)
  1877. {
  1878. UsCanvas.Children.Remove(contourExist);
  1879. UsCanvas.UnregisterName(contourName);
  1880. }
  1881. }
  1882. // 文字
  1883. string textName = "Organ_Text_" + organName;
  1884. TextBlock textExist = UsCanvas.FindName(textName) as TextBlock;
  1885. if (textExist != null)
  1886. {
  1887. UsCanvas.Children.Remove(textExist);
  1888. UsCanvas.UnregisterName(textName);
  1889. }
  1890. }
  1891. private void RemoveRoiInCanvas(string roiName, int roiContourNum)
  1892. {
  1893. // 框
  1894. string rectName = "ROI_Rect_" + roiName;
  1895. System.Windows.Shapes.Rectangle rectExist = UsCanvas.FindName(rectName) as System.Windows.Shapes.Rectangle;
  1896. if (rectExist != null)
  1897. {
  1898. UsCanvas.Children.Remove(rectExist);
  1899. UsCanvas.UnregisterName(rectName);
  1900. }
  1901. // 轮廓
  1902. for (int ni = 0; ni < roiContourNum; ni++)
  1903. {
  1904. string contourName = "ROI_Contour_" + roiName + "_" + ni;
  1905. System.Windows.Shapes.Polygon contourExist = UsCanvas.FindName(contourName) as System.Windows.Shapes.Polygon;
  1906. if (contourExist != null)
  1907. {
  1908. UsCanvas.Children.Remove(contourExist);
  1909. UsCanvas.UnregisterName(contourName);
  1910. }
  1911. System.Windows.Shapes.Polyline contourLineExist = UsCanvas.FindName(contourName) as System.Windows.Shapes.Polyline;
  1912. if (contourLineExist != null)
  1913. {
  1914. UsCanvas.Children.Remove(contourLineExist);
  1915. UsCanvas.UnregisterName(contourName);
  1916. }
  1917. }
  1918. // 文字
  1919. string textName = "ROI_Text_" + roiName;
  1920. TextBlock textExist = UsCanvas.FindName(textName) as TextBlock;
  1921. if (textExist != null)
  1922. {
  1923. UsCanvas.Children.Remove(textExist);
  1924. UsCanvas.UnregisterName(textName);
  1925. }
  1926. // 横轴
  1927. string lineHName = "ROI_LineH_" + roiName;
  1928. System.Windows.Shapes.Line lineHExist = UsCanvas.FindName(lineHName) as System.Windows.Shapes.Line;
  1929. if (lineHExist != null)
  1930. {
  1931. UsCanvas.Children.Remove(lineHExist);
  1932. UsCanvas.UnregisterName(lineHName);
  1933. }
  1934. // 纵轴
  1935. string lineVName = "ROI_LineV_" + roiName;
  1936. System.Windows.Shapes.Line lineVExist = UsCanvas.FindName(lineVName) as System.Windows.Shapes.Line;
  1937. if (lineVExist != null)
  1938. {
  1939. UsCanvas.Children.Remove(lineVExist);
  1940. UsCanvas.UnregisterName(lineVName);
  1941. }
  1942. }
  1943. private void CanvasSizeChanged(object sender, SizeChangedEventArgs e)
  1944. {
  1945. UpdateTransforms();
  1946. UpdateRois();
  1947. if (SettingConfig.Instance.IsShowOrgansContour)
  1948. {
  1949. UpdateOrgans();
  1950. }
  1951. }
  1952. private void OnCloseClick(object sender, RoutedEventArgs e)
  1953. {
  1954. if (_player != null)
  1955. {
  1956. _player.Stop();
  1957. _player.InputFrameReceived -= OnInputFrameReceived;
  1958. _player.FPSChanged -= OnFPSChanged;
  1959. }
  1960. StopDiagnosis();
  1961. Close();
  1962. }
  1963. private void OnRestoreClick(object sender, RoutedEventArgs e)
  1964. {
  1965. WindowState = WindowState.Normal;
  1966. }
  1967. private void OnMinClick(object sender, RoutedEventArgs e)
  1968. {
  1969. WindowState = WindowState.Minimized;
  1970. }
  1971. private void OnMaxClick(object sender, RoutedEventArgs e)
  1972. {
  1973. WindowState = WindowState.Maximized;
  1974. }
  1975. private void Window_StateChanged(object sender, EventArgs e)
  1976. {
  1977. if (WindowState == WindowState.Maximized)
  1978. {
  1979. MaxButton.Visibility = Visibility.Collapsed;
  1980. RestoreButton.Visibility = Visibility.Visible;
  1981. }
  1982. else
  1983. {
  1984. MaxButton.Visibility = Visibility.Visible;
  1985. RestoreButton.Visibility = Visibility.Collapsed;
  1986. }
  1987. }
  1988. private void Grid_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  1989. {
  1990. if (SettingConfig.Instance.IsVideo)
  1991. {
  1992. if (_isPlaying)
  1993. {
  1994. PauseButton.Visibility = Visibility.Visible;
  1995. }
  1996. }
  1997. }
  1998. private void Grid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
  1999. {
  2000. PauseButton.Visibility = Visibility.Collapsed;
  2001. }
  2002. private void OnExtractContours(object sender, RoutedEventArgs e)
  2003. {
  2004. if (_currentDetectedObject == null)
  2005. {
  2006. return;
  2007. }
  2008. var detectedObject = _currentDetectedObject;
  2009. var isLine = ExtractContoursBtn.IsChecked.Value;
  2010. if (ExtractContoursBtn.IsChecked.Value)
  2011. {
  2012. if (_myocardialDiagnosis != null)
  2013. {
  2014. detectedObject = _myocardialDiagnosis.ExtractContours(_currentDetectedObject);
  2015. }
  2016. }
  2017. RemoveRois();
  2018. var roiList = new List<Roi>();
  2019. if (detectedObject.Contours != null && detectedObject.Contours.Count() > 0)
  2020. {
  2021. var bondingBox = new MyRect(detectedObject.BoundingBox.Left, detectedObject.BoundingBox.Top, detectedObject.BoundingBox.Width, detectedObject.BoundingBox.Height);
  2022. var roi = new Roi(EnumOrgans.Null, bondingBox, detectedObject.Contours, System.Windows.Media.Brushes.Green, string.Empty, detectedObject.Confidence.ToString("0.0" + "%"), null);
  2023. roiList.Add(roi);
  2024. }
  2025. _rois = roiList;
  2026. // 更新画布上显示的Roi和Organ
  2027. UpdateRois(isLine);
  2028. }
  2029. }
  2030. }