BaseDiagnosis.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. public static double GetPhysicalPerPixel(VinnoImageData vinnoImageData, int index, bool isVinnoVid)
  156. {
  157. var vinnoImage = vinnoImageData.GetImage(index);
  158. double pixelLength;
  159. if (isVinnoVid)
  160. {
  161. pixelLength = GetLengthPerPxiel(vinnoImage);
  162. }
  163. else
  164. {
  165. pixelLength = GetPixelSpacingForVidExamData(vinnoImageData.ExtendedData);
  166. }
  167. return pixelLength;
  168. }
  169. private byte[] GetNewImageBuffer(byte[] imageData, DiagnosisPerImageModel diagResult, int imageWidth, int imageHeight, float widthPixelScale = 1, float heightPixelScale = 1)
  170. {
  171. var newImageBuffer = imageData;
  172. try
  173. {
  174. if (diagResult.DiagResultsForEachOrgan == null || diagResult.DiagResultsForEachOrgan.All(x => x.DetectedObjects.All(x => x.Label == 0)))
  175. {
  176. return newImageBuffer;
  177. }
  178. var skImageInfo = new SKImageInfo(imageWidth, imageHeight, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
  179. using (var surface = SKSurface.Create(skImageInfo))
  180. {
  181. var canvas = surface.Canvas;
  182. using (var bmp = SKBitmap.Decode(imageData))
  183. {
  184. canvas.DrawBitmap(bmp, SKRect.Create(imageWidth, imageHeight));
  185. var sizeRate = bmp.Height / 160.0;
  186. var fontSize = Convert.ToInt32(Math.Round(sizeRate * 6));
  187. var currentDetectInfos = new List<Tuple<AIDetectedObject, bool>>();
  188. List<SKPoint> kPoints = new List<SKPoint>();
  189. using (var rectangelPaint = new SKPaint { StrokeWidth = (float)sizeRate / 1.5f, Color = SKColors.Orange, Style = SKPaintStyle.Fill })
  190. {
  191. foreach (var record in diagResult.DiagResultsForEachOrgan)
  192. {
  193. if (record != null)
  194. {
  195. foreach (var detectedInfo in record.DetectedObjects)
  196. {
  197. if (detectedInfo.Label > 0 && detectedInfo.BoundingBox != null && detectedInfo.Descriptions != null && detectedInfo.Descriptions.Count() > 0)
  198. {
  199. var isMalignant = IsMalignant(detectedInfo);
  200. var color = isMalignant ? SKColors.Orange : SKColors.Lime;
  201. rectangelPaint.Color = color;
  202. var rect = detectedInfo.BoundingBox;
  203. var lesion = detectedInfo.Descriptions.FirstOrDefault(a => a.Type == DiagnosisDescription.LesionSize);
  204. if (lesion != null && !string.IsNullOrWhiteSpace(lesion.Value))
  205. {
  206. var lessionSizeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<AIDiagnosisLesionSize>(lesion.Value);
  207. if (lessionSizeInfo.HorizontalLengthInPixel > 0 && lessionSizeInfo.VerticalLengthInPixel > 0)
  208. {
  209. List<SKPoint> sKPoints = new List<SKPoint>();
  210. var kPoint = new SKPoint(-1, -1);
  211. foreach (var point in detectedInfo.Contours)
  212. {
  213. var poin = new SKPoint(point.X * widthPixelScale, point.Y * heightPixelScale);
  214. sKPoints.Add(poin);
  215. if ((kPoint.X < 0 && kPoint.Y < 0) || kPoint.X > poin.X)
  216. {
  217. kPoint = poin;
  218. }
  219. }
  220. kPoints.Add(kPoint);
  221. canvas.DrawPoints(SKPointMode.Points, sKPoints.ToArray(), rectangelPaint);
  222. List<SKPoint> sKPointLine = new List<SKPoint>();
  223. foreach (var item in detectedInfo.Descriptions)
  224. {
  225. if (item.Type == DiagnosisDescription.LesionSize && !string.IsNullOrWhiteSpace(item.Value))
  226. {
  227. JObject jobj = JObject.Parse(item.Value);
  228. foreach (var jobPoint in jobj)
  229. {
  230. if (!jobPoint.Key.Contains("Pixel"))
  231. {
  232. int x = Convert.ToInt32(jobPoint.Value.First.First);
  233. int y = Convert.ToInt32(jobPoint.Value.First.Next.First);
  234. sKPointLine.Add(new SKPoint(x, y));
  235. }
  236. }
  237. }
  238. }
  239. //横纵径虚线显示
  240. for (int j = 0; j < 2; j++)
  241. {
  242. float LineX = sKPointLine[2 * j].X * widthPixelScale - sKPointLine[2 * j + 1].X * widthPixelScale;
  243. float LineY = sKPointLine[2 * j].Y * heightPixelScale - sKPointLine[2 * j + 1].Y * heightPixelScale;
  244. double LineLength = Math.Sqrt(Math.Pow(LineX, 2) + Math.Pow(LineY, 2));
  245. float LineLengthX = (float)(LineX / LineLength);
  246. float LineLengthY = (float)(LineY / LineLength);
  247. List<SKPoint> sKLinePoint = new List<SKPoint>();
  248. for (int i = 0; i < LineLength; i = i + 10)
  249. {
  250. sKLinePoint.Add(new SKPoint(sKPointLine[2 * j + 1].X * widthPixelScale + LineLengthX * i, sKPointLine[2 * j + 1].Y * heightPixelScale + LineLengthY * i));
  251. }
  252. var linePaint = new SKPaint
  253. {
  254. StrokeWidth = (float)sizeRate / 2.5f,
  255. Color = color,
  256. Style = SKPaintStyle.Fill
  257. };
  258. canvas.DrawPoints(SKPointMode.Points, sKLinePoint.ToArray(), linePaint);
  259. 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);
  260. 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);
  261. 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);
  262. 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);
  263. }
  264. currentDetectInfos.Add(new Tuple<AIDetectedObject, bool>(detectedInfo, isMalignant));
  265. }
  266. }
  267. }
  268. }
  269. }
  270. }
  271. }
  272. //Draw Index
  273. using (var indexPaint = new SKPaint { Color = SKColors.Orange, StrokeWidth = (float)sizeRate, TextSize = fontSize, IsLinearText = true, IsAntialias = true })
  274. {
  275. var count = 1;
  276. foreach (var info in currentDetectInfos)
  277. {
  278. var detectedInfo = info.Item1;
  279. var color = info.Item2 ? SKColors.Orange : SKColors.Lime;
  280. if (detectedInfo.Label > 0 && detectedInfo.BoundingBox != null && detectedInfo.Descriptions != null && detectedInfo.Descriptions.Count() > 0)
  281. {
  282. indexPaint.Color = color;
  283. var tuple = new SKPoint(kPoints[count - 1].X - 25, kPoints[count - 1].Y) /*GetIndexPosition(currentDetectInfos, detectedInfo.BondingBox, bmp.Width, sizeRate)*/;
  284. canvas.DrawText(count.ToString(), tuple, indexPaint);
  285. count++;
  286. }
  287. }
  288. if (count > 1)
  289. {
  290. newImageBuffer = surface.Snapshot().Encode().ToArray();
  291. }
  292. }
  293. }
  294. }
  295. }
  296. catch (Exception ex)
  297. {
  298. Logger.WriteLineError("AI image draw rectangle fail," + ex);
  299. }
  300. return newImageBuffer;
  301. }
  302. private static double GetLengthPerPxiel(VinnoImage image)
  303. {
  304. var lengthPerPixel = 0.1;
  305. try
  306. {
  307. var visual = image.Visuals.FirstOrDefault(x => x is Vinno2DVisual) as Vinno2DVisual;
  308. if (visual != null)
  309. {
  310. var logicalCoordinates = visual.LogicalCoordinates;
  311. if (logicalCoordinates.Count > 0 && logicalCoordinates.ContainsKey(VinnoVisualAreaType.Tissue))
  312. {
  313. var logicInfo = logicalCoordinates[VinnoVisualAreaType.Tissue];
  314. var region = logicInfo.Region;
  315. var unit = logicInfo.XUnit;
  316. var depth = region.Height;
  317. var height = image.Height;
  318. if (height > 0)
  319. {
  320. lengthPerPixel = depth / height;
  321. }
  322. }
  323. }
  324. }
  325. catch (Exception ex)
  326. {
  327. Logger.WriteLineError($"Get pxiel length failed: {ex}");
  328. }
  329. return lengthPerPixel;
  330. }
  331. private static double GetPixelSpacingForVidExamData(byte[] extendedDatabytes)
  332. {
  333. var extendedData = VidExtendedData.FromBytes(extendedDatabytes);
  334. if (extendedData != null)
  335. {
  336. PixelSpacing pixelSpacing = new PixelSpacing();
  337. var pixelSpacingValue = GetVidValueByTag(DicomTagPixelSpacing, extendedData);
  338. if (pixelSpacingValue != null)
  339. {
  340. var pixelSpacingArray = pixelSpacingValue.GetValue().ToString().Split('\\');
  341. if (pixelSpacingArray.Length > 1)
  342. {
  343. if (double.TryParse(pixelSpacingArray[0], out double pixelSpacingX))
  344. {
  345. pixelSpacing.PhysicalDeltaX = pixelSpacingX;
  346. }
  347. if (double.TryParse(pixelSpacingArray[1], out double pixelSpacingY))
  348. {
  349. pixelSpacing.PhysicalDeltaY = pixelSpacingY;
  350. }
  351. }
  352. }
  353. else
  354. {
  355. pixelSpacing.PhysicalDeltaX = GetPhysicalDeltaX(extendedData);
  356. pixelSpacing.PhysicalDeltaY = GetPhysicalDeltaY(extendedData);
  357. }
  358. if (pixelSpacing.PhysicalDeltaX > 0)
  359. return pixelSpacing.PhysicalDeltaX / 10.0;
  360. if (pixelSpacing.PhysicalDeltaY > 0)
  361. return pixelSpacing.PhysicalDeltaY / 10.0;
  362. }
  363. return 0.1;
  364. }
  365. private static IVidValue GetVidValueByTag(VidTag vidTag, VidExtendedData extendedData)
  366. {
  367. IVidValue vidValue = null;
  368. var vidTagkey = extendedData.Data?.Keys.FirstOrDefault(v =>
  369. v.Group == vidTag.Group && v.Element == vidTag.Element);
  370. if (vidTagkey != null)
  371. {
  372. var flag = extendedData.Data?.TryGetValue(vidTagkey, out vidValue);
  373. if (flag.Value)
  374. {
  375. return vidValue;
  376. }
  377. }
  378. return null;
  379. }
  380. private static double GetPhysicalDeltaX(VidExtendedData extendedData)
  381. {
  382. IVidValue physicalDeltaXvalue = GetVidValueByTag(DicomTagPhysicalDeltaX, extendedData);
  383. if (physicalDeltaXvalue != null)
  384. {
  385. IVidValue physicalUnitsXvalue = GetVidValueByTag(DicomTagPhysicalUnitsX, extendedData);
  386. if (physicalUnitsXvalue != null)
  387. {
  388. var unitsvalue = Convert.ToInt16(physicalUnitsXvalue.GetValue().ToString());
  389. /// unit=3 is cm
  390. if (unitsvalue == 3)
  391. {
  392. var physicalDeltaX = Convert.ToDouble(physicalDeltaXvalue.GetValue().ToString()) * 10;
  393. if (physicalDeltaX > 0)
  394. return physicalDeltaX;
  395. }
  396. }
  397. }
  398. return 1.0;
  399. }
  400. private static double GetPhysicalDeltaY(VidExtendedData extendedData)
  401. {
  402. IVidValue physicalDeltaYvalue = GetVidValueByTag(DicomTagPhysicalDeltaY, extendedData);
  403. if (physicalDeltaYvalue != null)
  404. {
  405. IVidValue physicalUnitsYvalue = GetVidValueByTag(DicomTagPhysicalUnitsY, extendedData);
  406. if (physicalUnitsYvalue != null)
  407. {
  408. var unitsvalue = Convert.ToInt16(physicalUnitsYvalue.GetValue().ToString());
  409. /// unit=3 is cm
  410. if (unitsvalue == 3)
  411. {
  412. var physicalDeltaX = Convert.ToDouble(physicalDeltaYvalue.GetValue().ToString()) * 10;
  413. return physicalDeltaX;
  414. }
  415. }
  416. }
  417. return 1.0;
  418. }
  419. }
  420. }