BaseDiagnosis.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Newtonsoft.Json.Linq;
  6. using SkiaSharp;
  7. using Vinno.vCloud.Common.Vid2;
  8. using Vinno.vCloud.Common.Vid2.Visuals;
  9. using WingInterfaceLibrary.Enum;
  10. using WingServerCommon.Log;
  11. namespace WingAIDiagnosisService.Manage
  12. {
  13. public abstract class BaseDiagnosis
  14. {
  15. public DiagnosisOrganEnum Organ;
  16. public List<DiagnosisPerImageModel> RecordDiagnosisResult { get; set; } = new();
  17. private readonly string _tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DiagnosisTemp");
  18. private static readonly VidTag DicomTagPixelSpacing = new VidTag("0028", "0030");
  19. /// <summary>
  20. /// 0018, 602E Physical Delta Y
  21. /// </summary>
  22. private static readonly VidTag DicomTagPhysicalDeltaY = new VidTag("0018", "602E");
  23. /// <summary>
  24. /// 0018,602C Physical Delta X
  25. /// </summary>
  26. private static readonly VidTag DicomTagPhysicalDeltaX = new VidTag("0018", "602C");
  27. /// <summary>
  28. /// 0018, 6024 Physical Units X
  29. /// </summary>
  30. private static readonly VidTag DicomTagPhysicalUnitsX = new VidTag("0018", "6024");
  31. /// <summary>
  32. /// 0018, 6026 Physical Units Y
  33. /// </summary>
  34. private static readonly VidTag DicomTagPhysicalUnitsY = new VidTag("0018", "6026");
  35. public BaseDiagnosis(List<DiagnosisPerImageModel> recordResult, DiagnosisOrganEnum organ)
  36. {
  37. RecordDiagnosisResult = recordResult;
  38. Organ = organ;
  39. CheckDiagResultIndex();
  40. }
  41. /// <summary>筛选有效的AI诊断记录</summary>
  42. /// <param name="allResult"></param>
  43. /// <returns></returns>
  44. public virtual void CheckDiagResultIndex()
  45. {
  46. var validResult = new List<DiagnosisPerImageModel>();
  47. foreach (var diagResult in RecordDiagnosisResult)
  48. {
  49. var organResultList = new List<AIDiagnosisResultPerOrgan>();
  50. foreach (var organResult in diagResult.DiagResultsForEachOrgan)
  51. {
  52. var valid = CheckResultValid(organResult);
  53. if (valid != null)
  54. {
  55. organResultList.Add(valid);
  56. }
  57. }
  58. if (organResultList.Any())
  59. {
  60. diagResult.DiagResultsForEachOrgan = organResultList;
  61. validResult.Add(diagResult);
  62. }
  63. }
  64. RecordDiagnosisResult = validResult.OrderByDescending(x => x.PriorityScore).ToList();//根据评分倒序
  65. }
  66. /// <summary>筛选报告可用诊断结果</summary>
  67. /// <param name="validResults"></param>
  68. /// <returns></returns>
  69. public abstract List<DiagnosisPerImageModel> GetReportResults();
  70. /// <summary>判断并返回有效的诊断描述</summary>
  71. /// <param name="message"></param>
  72. /// <returns></returns>
  73. public abstract AIDiagnosisResultPerOrgan CheckResultValid(AIDiagnosisResultPerOrgan message);
  74. /// <summary>是否有病灶</summary>
  75. /// <param name="results"></param>
  76. /// <returns></returns>
  77. public bool HasSick()
  78. {
  79. foreach (var data in RecordDiagnosisResult)
  80. {
  81. var labels = data.GetLabels();
  82. if (labels.Any(x => x > 0))
  83. {
  84. return true;
  85. }
  86. }
  87. return false;
  88. }
  89. /// <summary>判断AI诊断结果</summary>
  90. /// <returns></returns>
  91. public abstract DiagnosisConclusion GetAIStatus();
  92. /// <summary>
  93. /// 是否恶性病灶
  94. /// </summary>
  95. /// <param name="label"></param>
  96. /// <returns></returns>
  97. protected abstract bool IsMalignant(AIDetectedObject detectedObject);
  98. /// <summary>计算最大尺寸</summary>
  99. /// <param name="detectedObjectInfo"></param>
  100. /// <returns></returns>
  101. protected double GetMaxLesionSize(AIDetectedObject detectedObjectInfo)
  102. {
  103. if (detectedObjectInfo.Descriptions == null || !detectedObjectInfo.Descriptions.Any())
  104. {
  105. return 0;
  106. }
  107. var descriptionList = detectedObjectInfo.Descriptions.Where(d => d?.Type == DiagnosisDescription.LesionSize);
  108. if (descriptionList == null || !descriptionList.Any())
  109. {
  110. return 0;
  111. }
  112. double currArea = 0;
  113. foreach (var lesion in detectedObjectInfo.Descriptions)
  114. {
  115. if (lesion.Type == DiagnosisDescription.LesionSize && !string.IsNullOrWhiteSpace(lesion.Value))
  116. {
  117. var lessionSizeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<AIDiagnosisLesionSize>(lesion.Value);
  118. var area = lessionSizeInfo.HorizontalLengthInPixel * lessionSizeInfo.VerticalLengthInPixel;
  119. if (area > currArea)
  120. {
  121. currArea = area;
  122. }
  123. }
  124. }
  125. return currArea;
  126. }
  127. protected void InitialAIImage()
  128. {
  129. foreach (var remedical in RecordDiagnosisResult)
  130. {
  131. var result = GetAIImageInfo(remedical);
  132. remedical.Pixel = result.Item1;
  133. remedical.AILocalImagePath = result.Item2;
  134. }
  135. }
  136. protected Tuple<double, string> GetAIImageInfo(DiagnosisPerImageModel diagResult)
  137. {
  138. var vinnoImageData = new VinnoImageData(diagResult.LocalVidPath, OperationMode.Open);
  139. var vinnoImage = vinnoImageData.GetImage(diagResult.Index);
  140. double pixelLength;
  141. if (diagResult.IsVinnoVid)
  142. {
  143. pixelLength = GetLengthPerPxiel(vinnoImage);
  144. }
  145. else
  146. {
  147. pixelLength = GetPixelSpacingForVidExamData(vinnoImageData.ExtendedData);
  148. }
  149. var newBytes = GetNewImageBuffer(vinnoImage.ImageData, diagResult, vinnoImage.Width, vinnoImage.Height);
  150. var aiLocalFile = Path.Combine(_tempFolder, $"{Guid.NewGuid():N}.jpg");
  151. File.WriteAllBytes(aiLocalFile, newBytes);
  152. vinnoImageData.Dispose();
  153. return new Tuple<double, string>(pixelLength, aiLocalFile);
  154. }
  155. private byte[] GetNewImageBuffer(byte[] imageData, DiagnosisPerImageModel diagResult, int imageWidth, int imageHeight, float widthPixelScale = 1, float heightPixelScale = 1)
  156. {
  157. var newImageBuffer = imageData;
  158. try
  159. {
  160. if (diagResult.DiagResultsForEachOrgan == null || diagResult.DiagResultsForEachOrgan.All(x => x.DetectedObjects.All(x => x.Label == 0)))
  161. {
  162. return newImageBuffer;
  163. }
  164. var skImageInfo = new SKImageInfo(imageWidth, imageHeight, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
  165. using (var surface = SKSurface.Create(skImageInfo))
  166. {
  167. var canvas = surface.Canvas;
  168. using (var bmp = SKBitmap.Decode(imageData))
  169. {
  170. canvas.DrawBitmap(bmp, SKRect.Create(imageWidth, imageHeight));
  171. var sizeRate = bmp.Height / 160.0;
  172. var fontSize = Convert.ToInt32(Math.Round(sizeRate * 6));
  173. var currentDetectInfos = new List<Tuple<AIDetectedObject, bool>>();
  174. List<SKPoint> kPoints = new List<SKPoint>();
  175. using (var rectangelPaint = new SKPaint { StrokeWidth = (float)sizeRate / 1.5f, Color = SKColors.Orange, Style = SKPaintStyle.Fill })
  176. {
  177. foreach (var record in diagResult.DiagResultsForEachOrgan)
  178. {
  179. if (record != null)
  180. {
  181. foreach (var detectedInfo in record.DetectedObjects)
  182. {
  183. if (detectedInfo.Label > 0 && detectedInfo.BoundingBox != null && detectedInfo.Descriptions != null && detectedInfo.Descriptions.Count() > 0)
  184. {
  185. var isMalignant = IsMalignant(detectedInfo);
  186. var color = isMalignant ? SKColors.Orange : SKColors.Lime;
  187. rectangelPaint.Color = color;
  188. var rect = detectedInfo.BoundingBox;
  189. var lesion = detectedInfo.Descriptions.FirstOrDefault(a => a.Type == DiagnosisDescription.LesionSize);
  190. if (lesion != null && !string.IsNullOrWhiteSpace(lesion.Value))
  191. {
  192. var lessionSizeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<AIDiagnosisLesionSize>(lesion.Value);
  193. if (lessionSizeInfo.HorizontalLengthInPixel > 0 && lessionSizeInfo.VerticalLengthInPixel > 0)
  194. {
  195. List<SKPoint> sKPoints = new List<SKPoint>();
  196. int index = 0;
  197. var kPoint = new SKPoint(-1, -1);
  198. foreach (var point in detectedInfo.Contours)
  199. {
  200. if (index % 10 == 0)
  201. {
  202. var poin = new SKPoint(point.X * widthPixelScale, point.Y * heightPixelScale);
  203. sKPoints.Add(poin);
  204. if ((kPoint.X < 0 && kPoint.Y < 0) || kPoint.X > poin.X)
  205. {
  206. kPoint = poin;
  207. }
  208. }
  209. index++;
  210. }
  211. kPoints.Add(kPoint);
  212. canvas.DrawPoints(SKPointMode.Points, sKPoints.ToArray(), rectangelPaint);
  213. List<SKPoint> sKPointLine = new List<SKPoint>();
  214. foreach (var item in detectedInfo.Descriptions)
  215. {
  216. if (item.Type == DiagnosisDescription.LesionSize && !string.IsNullOrWhiteSpace(item.Value))
  217. {
  218. JObject jobj = JObject.Parse(item.Value);
  219. foreach (var jobPoint in jobj)
  220. {
  221. if (!jobPoint.Key.Contains("Pixel"))
  222. {
  223. int x = Convert.ToInt32(jobPoint.Value.First.First);
  224. int y = Convert.ToInt32(jobPoint.Value.First.Next.First);
  225. sKPointLine.Add(new SKPoint(x, y));
  226. }
  227. }
  228. }
  229. }
  230. //横纵径虚线显示
  231. for (int j = 0; j < 2; j++)
  232. {
  233. float LineX = sKPointLine[2 * j].X * widthPixelScale - sKPointLine[2 * j + 1].X * widthPixelScale;
  234. float LineY = sKPointLine[2 * j].Y * heightPixelScale - sKPointLine[2 * j + 1].Y * heightPixelScale;
  235. double LineLength = Math.Sqrt(Math.Pow(LineX, 2) + Math.Pow(LineY, 2));
  236. float LineLengthX = (float)(LineX / LineLength);
  237. float LineLengthY = (float)(LineY / LineLength);
  238. List<SKPoint> sKLinePoint = new List<SKPoint>();
  239. for (int i = 0; i < LineLength; i = i + 10)
  240. {
  241. sKLinePoint.Add(new SKPoint(sKPointLine[2 * j + 1].X * widthPixelScale + LineLengthX * i, sKPointLine[2 * j + 1].Y * heightPixelScale + LineLengthY * i));
  242. }
  243. var linePaint = new SKPaint
  244. {
  245. StrokeWidth = (float)sizeRate / 2.5f,
  246. Color = color,
  247. Style = SKPaintStyle.Fill
  248. };
  249. canvas.DrawPoints(SKPointMode.Points, sKLinePoint.ToArray(), linePaint);
  250. canvas.DrawLine(new SKPoint(sKPointLine[2 * j].X * widthPixelScale - 5, sKPointLine[2 * j].Y * heightPixelScale), new SKPoint(sKPointLine[2 * j].X * (float)widthPixelScale + 5, sKPointLine[2 * j].Y * (float)heightPixelScale), linePaint);
  251. canvas.DrawLine(new SKPoint(sKPointLine[2 * j].X * widthPixelScale, sKPointLine[2 * j].Y * heightPixelScale - 5), new SKPoint(sKPointLine[2 * j].X * (float)widthPixelScale, sKPointLine[2 * j].Y * (float)heightPixelScale + 5), linePaint);
  252. canvas.DrawLine(new SKPoint(sKPointLine[2 * j + 1].X * widthPixelScale - 5, sKPointLine[2 * j + 1].Y * heightPixelScale), new SKPoint(sKPointLine[2 * j + 1].X * widthPixelScale + 5, sKPointLine[2 * j + 1].Y * heightPixelScale), linePaint);
  253. canvas.DrawLine(new SKPoint(sKPointLine[2 * j + 1].X * widthPixelScale, sKPointLine[2 * j + 1].Y * heightPixelScale - 5), new SKPoint(sKPointLine[2 * j + 1].X * widthPixelScale, sKPointLine[2 * j + 1].Y * heightPixelScale + 5), linePaint);
  254. }
  255. currentDetectInfos.Add(new Tuple<AIDetectedObject, bool>(detectedInfo, isMalignant));
  256. }
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. //Draw Index
  264. using (var indexPaint = new SKPaint { Color = SKColors.Orange, StrokeWidth = (float)sizeRate, TextSize = fontSize, IsLinearText = true, IsAntialias = true })
  265. {
  266. var count = 1;
  267. foreach (var info in currentDetectInfos)
  268. {
  269. var detectedInfo = info.Item1;
  270. var color = info.Item2 ? SKColors.Orange : SKColors.Lime;
  271. if (detectedInfo.Label > 0 && detectedInfo.BoundingBox != null && detectedInfo.Descriptions != null && detectedInfo.Descriptions.Count() > 0)
  272. {
  273. indexPaint.Color = color;
  274. var tuple = new SKPoint(kPoints[count - 1].X - 25, kPoints[count - 1].Y) /*GetIndexPosition(currentDetectInfos, detectedInfo.BondingBox, bmp.Width, sizeRate)*/;
  275. canvas.DrawText(count.ToString(), tuple, indexPaint);
  276. count++;
  277. }
  278. }
  279. if (count > 1)
  280. {
  281. newImageBuffer = surface.Snapshot().Encode().ToArray();
  282. }
  283. }
  284. }
  285. }
  286. }
  287. catch (Exception ex)
  288. {
  289. Logger.WriteLineError("AI image draw rectangle fail," + ex);
  290. }
  291. return newImageBuffer;
  292. }
  293. private double GetLengthPerPxiel(VinnoImage image)
  294. {
  295. var lengthPerPixel = 0.1;
  296. try
  297. {
  298. var visual = image.Visuals.FirstOrDefault(x => x is Vinno2DVisual) as Vinno2DVisual;
  299. if (visual != null)
  300. {
  301. var logicalCoordinates = visual.LogicalCoordinates;
  302. if (logicalCoordinates.Count > 0 && logicalCoordinates.ContainsKey(VinnoVisualAreaType.Tissue))
  303. {
  304. var logicInfo = logicalCoordinates[VinnoVisualAreaType.Tissue];
  305. var region = logicInfo.Region;
  306. var unit = logicInfo.XUnit;
  307. var depth = region.Height;
  308. var height = image.Height;
  309. if (height > 0)
  310. {
  311. lengthPerPixel = depth / height;
  312. }
  313. }
  314. }
  315. }
  316. catch (Exception ex)
  317. {
  318. Logger.WriteLineError($"Get pxiel length failed: {ex}");
  319. }
  320. return lengthPerPixel;
  321. }
  322. private double GetPixelSpacingForVidExamData(byte[] extendedDatabytes)
  323. {
  324. var extendedData = VidExtendedData.FromBytes(extendedDatabytes);
  325. if (extendedData != null)
  326. {
  327. PixelSpacing pixelSpacing = new PixelSpacing();
  328. var pixelSpacingValue = GetVidValueByTag(DicomTagPixelSpacing, extendedData);
  329. if (pixelSpacingValue != null)
  330. {
  331. var pixelSpacingArray = pixelSpacingValue.GetValue().ToString().Split('\\');
  332. if (pixelSpacingArray.Length > 1)
  333. {
  334. if (double.TryParse(pixelSpacingArray[0], out double pixelSpacingX))
  335. {
  336. pixelSpacing.PhysicalDeltaX = pixelSpacingX;
  337. }
  338. if (double.TryParse(pixelSpacingArray[1], out double pixelSpacingY))
  339. {
  340. pixelSpacing.PhysicalDeltaY = pixelSpacingY;
  341. }
  342. }
  343. }
  344. else
  345. {
  346. pixelSpacing.PhysicalDeltaX = GetPhysicalDeltaX(extendedData);
  347. pixelSpacing.PhysicalDeltaY = GetPhysicalDeltaY(extendedData);
  348. }
  349. if (pixelSpacing.PhysicalDeltaX > 0)
  350. return pixelSpacing.PhysicalDeltaX / 10.0;
  351. if (pixelSpacing.PhysicalDeltaY > 0)
  352. return pixelSpacing.PhysicalDeltaY / 10.0;
  353. }
  354. return 0.1;
  355. }
  356. private IVidValue GetVidValueByTag(VidTag vidTag, VidExtendedData extendedData)
  357. {
  358. IVidValue vidValue = null;
  359. var vidTagkey = extendedData.Data?.Keys.FirstOrDefault(v =>
  360. v.Group == vidTag.Group && v.Element == vidTag.Element);
  361. if (vidTagkey != null)
  362. {
  363. var flag = extendedData.Data?.TryGetValue(vidTagkey, out vidValue);
  364. if (flag.Value)
  365. {
  366. return vidValue;
  367. }
  368. }
  369. return null;
  370. }
  371. private double GetPhysicalDeltaX(VidExtendedData extendedData)
  372. {
  373. IVidValue physicalDeltaXvalue = GetVidValueByTag(DicomTagPhysicalDeltaX, extendedData);
  374. if (physicalDeltaXvalue != null)
  375. {
  376. IVidValue physicalUnitsXvalue = GetVidValueByTag(DicomTagPhysicalUnitsX, extendedData);
  377. if (physicalUnitsXvalue != null)
  378. {
  379. var unitsvalue = Convert.ToInt16(physicalUnitsXvalue.GetValue().ToString());
  380. /// unit=3 is cm
  381. if (unitsvalue == 3)
  382. {
  383. var physicalDeltaX = Convert.ToDouble(physicalDeltaXvalue.GetValue().ToString()) * 10;
  384. if (physicalDeltaX > 0)
  385. return physicalDeltaX;
  386. }
  387. }
  388. }
  389. return 1.0;
  390. }
  391. private double GetPhysicalDeltaY(VidExtendedData extendedData)
  392. {
  393. IVidValue physicalDeltaYvalue = GetVidValueByTag(DicomTagPhysicalDeltaY, extendedData);
  394. if (physicalDeltaYvalue != null)
  395. {
  396. IVidValue physicalUnitsYvalue = GetVidValueByTag(DicomTagPhysicalUnitsY, extendedData);
  397. if (physicalUnitsYvalue != null)
  398. {
  399. var unitsvalue = Convert.ToInt16(physicalUnitsYvalue.GetValue().ToString());
  400. /// unit=3 is cm
  401. if (unitsvalue == 3)
  402. {
  403. var physicalDeltaX = Convert.ToDouble(physicalDeltaYvalue.GetValue().ToString()) * 10;
  404. return physicalDeltaX;
  405. }
  406. }
  407. }
  408. return 1.0;
  409. }
  410. }
  411. }