HumanSurfaceOrganAnalyser.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. using AI.Common;
  2. using AI.Common.Log;
  3. using HumanOrganSegmentDemo;
  4. using RUSInferNet.Vision;
  5. using RUSInferNet;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using HumanOrganSegDemo.HumanBodyDetector;
  15. using HumanOrganSegDemo.HumanBodyPartAnalyser.OrganSegment;
  16. using HumanOrganSegDemo.HumanSurfaceOrganAnalyser.HumanPoseEstimate;
  17. using System.Windows.Media;
  18. using RUSInferNet.PostProcess;
  19. namespace HumanOrganSegDemo.HumanBodyPartAnalyser
  20. {
  21. public class HumanSurfaceOrganAnalyser : IHumanSurfaceOrganAnalyser
  22. {
  23. #region private
  24. private IHumanDetector _humanDetector;
  25. private IHumanPoseEstimate _humanPoseEstimate;
  26. private IHumanSurfaceOrganSegment _surfaceOrganSeg;
  27. /// <summary>
  28. /// 像素坐标系下人体朝向的方向向量
  29. /// </summary>
  30. public Point2D _humanOrientationInPCS;
  31. // 是否完成了人体朝向分析
  32. public volatile bool _orientationFinish = false;
  33. public Dictionary<EnumHumanParts, Rect[]> _bodyPartBoundBoxesAll = new Dictionary<EnumHumanParts, Rect[]>();
  34. public BodyKeyPoints _bodyKeyPoints;
  35. public ContourPoints _organContours;
  36. /// <summary>
  37. /// 是否启用推理
  38. /// </summary>
  39. private volatile bool _enable = false;
  40. private ConcurrentQueue<RawImage> _inputImages = new ConcurrentQueue<RawImage>();
  41. private readonly ManualResetEvent _waitImageEvent = new ManualResetEvent(true);
  42. private readonly ManualResetEvent _processFinishEvent = new ManualResetEvent(true);
  43. private Thread _imageProcessThread;
  44. private volatile bool _disposing = false;
  45. private const int _queueMaxSize = 1;
  46. #endregion
  47. #region 实现
  48. /// <summary>
  49. /// 是否启用推理
  50. /// </summary>
  51. /// <returns></returns>
  52. public bool Enable
  53. {
  54. get { return _enable; }
  55. set { _enable = value; }
  56. }
  57. public void EvaluateOneImage(RawImage image)
  58. {
  59. if (_enable)
  60. {
  61. _inputImages.Enqueue(image.Clone());
  62. _waitImageEvent.Set();
  63. if (_imageProcessThread == null || !_imageProcessThread.IsAlive)
  64. {
  65. _imageProcessThread = new Thread(() => DoImageProcess())
  66. {
  67. IsBackground = true,
  68. Name = "HumanSurfaceOrganAnalyser_Process"
  69. };
  70. _imageProcessThread.Start();
  71. }
  72. }
  73. }
  74. /// <summary>
  75. /// 通知订阅者,人体检测有结果更新
  76. /// </summary>
  77. public event EventHandler<HumanDetectResultPerImage> NotifyHumanDetectFinish;
  78. /// <summary>
  79. /// 通知订阅者,推理过程中发生了错误
  80. /// </summary>
  81. public event EventHandler<ErrorEventArgs> NotifyError;
  82. /// <summary>
  83. /// 通知订阅者,有log要记
  84. /// </summary>
  85. public event EventHandler<LogEventArgs> NotifyLogWrite;
  86. /// <summary>
  87. /// 销毁
  88. /// </summary>
  89. public void Dispose()
  90. {
  91. DoDispose();
  92. GC.SuppressFinalize(this);
  93. }
  94. /// <summary>
  95. /// 析构函数
  96. /// </summary>
  97. ~HumanSurfaceOrganAnalyser()
  98. {
  99. DoDispose();
  100. }
  101. #endregion
  102. #region constructor
  103. public HumanSurfaceOrganAnalyser(EnumOrgans organName,int numCpu, string netDir)
  104. {
  105. _humanDetector = new HumanBodyPartDetector(numCpu, netDir);
  106. _humanPoseEstimate = new HumanPoseEstimate(numCpu, netDir);
  107. switch (organName)
  108. {
  109. case EnumOrgans.Heart:
  110. _surfaceOrganSeg = new HumanSurfaceHeartSegment(numCpu, netDir);
  111. break;
  112. case EnumOrgans.Liver:
  113. _surfaceOrganSeg = new HumanSurfaceLiverSegment(numCpu, netDir);
  114. break;
  115. default:
  116. throw new ArgumentException("Invalid Organ name!");
  117. }
  118. _humanDetector.NotifyLogWrite += OnLogWrite;
  119. _humanDetector.NotifyError += OnErrorOccur;
  120. _humanPoseEstimate.NotifyLogWrite += OnLogWrite;
  121. _humanPoseEstimate.NotifyError += OnErrorOccur;
  122. _surfaceOrganSeg.NotifyLogWrite += OnLogWrite;
  123. _surfaceOrganSeg.NotifyError += OnErrorOccur;
  124. }
  125. #endregion
  126. #region private funcs
  127. private void DoImageProcess()
  128. {
  129. while (!_disposing)
  130. {
  131. if (_inputImages.Count > 0)
  132. {
  133. _inputImages.TryDequeue(out RawImage image);
  134. // 如果队列里待处理的数据过多,则对该图不做处理,直接跳到下一幅图
  135. if (_inputImages.Count >= _queueMaxSize)
  136. {
  137. image.Dispose();
  138. continue;
  139. }
  140. try
  141. {
  142. // 让dispose的线程等待执行完毕后再销毁
  143. _processFinishEvent.Reset();
  144. var totalStartTime = Environment.TickCount;
  145. var imageWidth = image.Width;
  146. var imageHeight = image.Height;
  147. //清空历史数据
  148. if (_bodyPartBoundBoxesAll != null)
  149. {
  150. _bodyPartBoundBoxesAll.Clear();
  151. }
  152. _humanOrientationInPCS = new Point2D(0, 0);
  153. _bodyKeyPoints = new BodyKeyPoints();
  154. _organContours = new ContourPoints();
  155. Rect humanRc = new Rect();
  156. Rect faceRc=new Rect();
  157. // 目标检测(人体和人脸)
  158. var detectedHumans = _humanDetector.EvaluateOneImage(image);
  159. // 对检测出的人体框(可能是多个框)进行分析,决策出一个输出框作为目标
  160. HumanDetectResultProcess(detectedHumans, out humanRc,out faceRc);
  161. //检测出了有效人体框
  162. if (humanRc.Width * humanRc.Height >0)
  163. {
  164. // 对ROI区域内的人体进行体表器官分割
  165. var result = _surfaceOrganSeg.EvaluateOneImage(image, humanRc);
  166. //依据人脸(假如有)分析人体朝向,没有则依据轮廓与关键点计算人体朝向向量
  167. EvaluateHumanOrientationInPCS(image,humanRc, faceRc,result);
  168. }
  169. // 用过后的图像销毁
  170. image.Dispose();
  171. // 执行完毕了,dispose的线程可以开始销毁了
  172. _processFinishEvent.Set();
  173. //运行耗时
  174. var totalTime = Environment.TickCount - totalStartTime;
  175. int timeElapsed = totalTime;
  176. // 通知订阅者,预处理的结果有更新
  177. NotifyHumanDetectFinish?.Invoke(this, new HumanDetectResultPerImage(_bodyPartBoundBoxesAll, humanRc, _bodyKeyPoints, _humanOrientationInPCS, _organContours, timeElapsed));
  178. }
  179. catch (Exception excep)
  180. {
  181. _processFinishEvent.Set();
  182. NotifyError?.Invoke(this, new ErrorEventArgs(excep));
  183. }
  184. }
  185. else
  186. {
  187. // 如果已经没有要处理的数据了,就等有新数据输入的时候再继续while循环
  188. _waitImageEvent.Reset();
  189. _waitImageEvent.WaitOne();
  190. }
  191. Thread.Sleep(1);
  192. }
  193. }
  194. /// <summary>
  195. /// 人体检测结果处理 todo
  196. /// 1:提取人体框(作为分割模块的ROI)
  197. /// 2:提取人脸框
  198. /// </summary>
  199. /// <param name="humans"></param>
  200. /// <returns></returns>
  201. /// <exception cref="ArgumentException"></exception>
  202. private void HumanDetectResultProcess(IDetectedObject[] humans, out Rect HumanRect,out Rect FaceRect)
  203. {
  204. _orientationFinish = false;
  205. List<Rect> humanRect = new List<Rect>();
  206. List<Rect> faceRect = new List<Rect>();
  207. HumanRect=new Rect();
  208. FaceRect=new Rect();
  209. List<float> humanConfidence = new List<float>();
  210. for (int i =0; i< humans.Length; ++i)
  211. {
  212. switch (humans[i].Label)
  213. {
  214. case 1:
  215. faceRect.Add(humans[i].BoundingBox);
  216. break;
  217. case 2:
  218. humanRect.Add(humans[i].BoundingBox);
  219. humanConfidence.Add(humans[i].Confidence);
  220. break;
  221. default:
  222. throw new ArgumentException("Invalid humans part label!");
  223. }
  224. }
  225. _bodyPartBoundBoxesAll.Add(EnumHumanParts.Head, faceRect.ToArray());
  226. _bodyPartBoundBoxesAll.Add(EnumHumanParts.Body, humanRect.ToArray());
  227. // todo 一幅图里出现多个人或者多张脸,需要用做处理
  228. // 临时实现方案
  229. //出现多个人,取置信度最高的框
  230. List<float> temp = new List<float>();
  231. if (humanRect.Count > 0)
  232. {
  233. for (int i = 0; i < humanRect.Count; i++)
  234. {
  235. temp.Add(humanConfidence[i]);
  236. }
  237. temp.Sort();
  238. for (int j = 0; j < temp.Count; j++)
  239. {
  240. if (humanConfidence[j] == temp[temp.Count - 1])
  241. {
  242. HumanRect = humanRect[j];
  243. }
  244. }
  245. // 只出现一张脸时返回结果框
  246. if (faceRect.Count == 1)
  247. {
  248. FaceRect=faceRect[0];
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// 得到轮廓并计算人体朝向
  254. /// </summary>
  255. /// <param name="image"></param>
  256. /// <param name="HumanRoi"></param>
  257. /// <param name="ContoursResult"></param>
  258. private void EvaluateHumanOrientationInPCS(RawImage image,Rect HumanRoi, Rect FaceRoi,IDetectedObject[] ContoursResult)
  259. {
  260. int midX, midY;
  261. Point2D bodyKeyPtsPoint = new Point2D(0, 0);
  262. Point2D humanCenter = new Point2D(0, 0);
  263. Point2D faceCenter = new Point2D(0, 0);
  264. //依据人脸框和人体框给出人体朝向向量
  265. if (FaceRoi.Width* FaceRoi.Height>0)
  266. {
  267. humanCenter = new Point2D(HumanRoi.Left + HumanRoi.Width / 2, HumanRoi.Top + HumanRoi.Height / 2);
  268. faceCenter = new Point2D(FaceRoi.Left + FaceRoi.Width / 2, FaceRoi.Top + FaceRoi.Height / 2);
  269. _humanOrientationInPCS = new Point2D(faceCenter.X - humanCenter.X, faceCenter.Y - humanCenter.Y);
  270. _orientationFinish = true;
  271. }
  272. //得到轮廓点
  273. if (ContoursResult.Length > 0 && ContoursResult[0].Contour != null && ContoursResult[0].Contour.Contours.Length > 0)
  274. {
  275. _organContours = ContoursResult[0].Contour.Contours[0];
  276. int len = ContoursResult[0].Contour.Contours[0].Points.Length;
  277. //轮廓中心点
  278. List<int> contoursX = new List<int>();
  279. List<int> contoursY = new List<int>();
  280. for (int i = 0; i < len; i++)
  281. {
  282. contoursX.Add(ContoursResult[0].Contour.Contours[0].Points[i].X);
  283. contoursY.Add(ContoursResult[0].Contour.Contours[0].Points[i].Y);
  284. }
  285. contoursX.Sort();
  286. contoursY.Sort();
  287. midX = (contoursX[0] + contoursX[len - 1]) / 2;
  288. midY = (contoursY[0] + contoursY[len - 1]) / 2;
  289. }
  290. //人体框中心点
  291. else
  292. {
  293. midX = HumanRoi.Left + HumanRoi.Width / 2;
  294. midY = HumanRoi.Top + HumanRoi.Height / 2;
  295. }
  296. // 如果没有分析出人体朝向,则调用关键点检测模型进行关节提取并分析人体朝向
  297. if (!_orientationFinish)
  298. {
  299. var bodyKeyPts = _humanPoseEstimate.EvaluateOneImage(image, HumanRoi);
  300. List<float> temp = new List<float>();
  301. // todo 已经限制了roi,最多检测出一个人,如果检测不到或者检测多个人的关节点,都不做处理
  302. if (bodyKeyPts.Length > 0)
  303. {
  304. for (int i = 0; i < bodyKeyPts.Length; i++)
  305. {
  306. temp.Add(bodyKeyPts[i].Confidence);
  307. }
  308. //选取置信度高的人,如果不包含上半身关键点则找次高置信度,依此类推
  309. temp.Sort();
  310. for (int i = 0; i < bodyKeyPts.Length; i++)
  311. {
  312. for (int j = 0; j < temp.Count; j++)
  313. {
  314. if (bodyKeyPts[j].Confidence == temp[temp.Count - i - 1])
  315. {
  316. bodyKeyPtsPoint = HumanKeyPtsProcess((DetectedHuman)bodyKeyPts[j]);
  317. if (bodyKeyPtsPoint.X != 0 || bodyKeyPtsPoint.Y != 0)
  318. {
  319. i = bodyKeyPts.Length;
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. _humanOrientationInPCS = new Point2D(bodyKeyPtsPoint.X - midX, bodyKeyPtsPoint.Y - midY);
  326. }
  327. }
  328. }
  329. /// <summary>
  330. /// 依据关键点进行人体朝向分析 todo
  331. /// </summary>
  332. /// <param name="humansKeyPts"></param>
  333. /// <returns></returns>
  334. private Point2D HumanKeyPtsProcess(DetectedHuman humansKeyPts)
  335. {
  336. // todo
  337. _bodyKeyPoints = humansKeyPts.KeyPoints;
  338. if (_bodyKeyPoints.Neck.X>0)
  339. {
  340. return _bodyKeyPoints.Neck;
  341. }
  342. else if (_bodyKeyPoints.LeftShoulder.X > 0)
  343. {
  344. return _bodyKeyPoints.LeftShoulder;
  345. }
  346. else if (_bodyKeyPoints.RightShoulder.X > 0)
  347. {
  348. return _bodyKeyPoints.RightShoulder;
  349. }
  350. else
  351. {
  352. return new Point2D(0, 0);
  353. }
  354. }
  355. /// <summary>
  356. /// 主动销毁
  357. /// </summary>
  358. private void DoDispose()
  359. {
  360. if (!_disposing)
  361. {
  362. _disposing = true;
  363. _waitImageEvent.Set();
  364. _processFinishEvent.WaitOne();
  365. if (_humanDetector != null)
  366. {
  367. _humanDetector.Dispose();
  368. _humanDetector.NotifyLogWrite -= OnLogWrite;
  369. _humanDetector.NotifyError -= OnErrorOccur;
  370. _humanDetector = null;
  371. }
  372. if (_humanPoseEstimate != null)
  373. {
  374. _humanPoseEstimate.Dispose();
  375. _humanPoseEstimate.NotifyLogWrite -= OnLogWrite;
  376. _humanPoseEstimate.NotifyError -= OnErrorOccur;
  377. _humanPoseEstimate = null;
  378. }
  379. if (_surfaceOrganSeg != null)
  380. {
  381. _surfaceOrganSeg.Dispose();
  382. _surfaceOrganSeg.NotifyLogWrite -= OnLogWrite;
  383. _surfaceOrganSeg.NotifyError -= OnErrorOccur;
  384. _surfaceOrganSeg = null;
  385. }
  386. while (_inputImages.Count > 0)
  387. {
  388. if (_inputImages.TryDequeue(out var input))
  389. {
  390. input?.Dispose();
  391. }
  392. }
  393. }
  394. }
  395. /// <summary>
  396. /// 有log要记
  397. /// </summary>
  398. /// <param name="sender"></param>
  399. /// <param name="e"></param>
  400. private void OnLogWrite(object sender, LogEventArgs e)
  401. {
  402. NotifyLogWrite?.Invoke(sender, e);
  403. }
  404. /// <summary>
  405. /// 有错误发生
  406. /// </summary>
  407. /// <param name="sender"></param>
  408. /// <param name="e"></param>
  409. private void OnErrorOccur(object sender, ErrorEventArgs e)
  410. {
  411. NotifyError?.Invoke(sender, e);
  412. }
  413. #endregion
  414. }
  415. }