PalmDetector.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Drawing;
  7. using Emgu.CV;
  8. using Emgu.CV.Structure;
  9. using bbiwarg.Utility;
  10. using bbiwarg.Images;
  11. using bbiwarg.Detectors.FingerDetection;
  12. using bbiwarg.Graphics;
  13. namespace bbiwarg.Detectors.PalmDetection
  14. {
  15. class PalmDetector
  16. {
  17. private int width, height;
  18. private OutputImage outputImage;
  19. private EdgeImage edgeImage;
  20. private Image<Gray, Byte> handImage;
  21. private Image<Gray, Byte> pointingHandMask;
  22. private List<Finger> fingers;
  23. private Contour<Point> palmContour;
  24. private List<MCvConvexityDefect> convexityDefects;
  25. private Vector2D thumbDefectStart;
  26. private Vector2D thumbDefectEnd;
  27. private Vector2D thumbDefectDepth, lastThumbDefectDepth;
  28. private Kalman2DPositionFilter thumbDefectDepthFilter, thumbDefectStartFilter, thumbDefectEndFilter;
  29. private Vector2D topLeft;
  30. private Vector2D topRight;
  31. private Vector2D bottomLeft;
  32. private Vector2D bottomRight;
  33. public Quadrangle PalmQuad { get; private set; }
  34. public PalmDetector()
  35. {
  36. // TODO: determine which fingers are index or thumb-fingers and detect palm in thumb-hand
  37. thumbDefectDepthFilter = new Kalman2DPositionFilter(1.0e-2f, 1.0e-2f);
  38. thumbDefectStartFilter = new Kalman2DPositionFilter(1.0e-2f, 1.0e-2f);
  39. thumbDefectEndFilter = new Kalman2DPositionFilter(1.0e-2f, 1.0e-2f);
  40. }
  41. public void findPalmQuad(DepthImage depthImage, EdgeImage edgeImage, OutputImage outputImage, List<Finger> trackedFingers)
  42. {
  43. this.width = depthImage.Width;
  44. this.height = depthImage.Height;
  45. i1 = new OutputImage(width, height);
  46. i2 = new OutputImage(width, height);
  47. i3 = new OutputImage(width, height);
  48. i4 = new OutputImage(width, height);
  49. i5 = new OutputImage(width, height);
  50. i6 = new OutputImage(width, height);
  51. i7 = new OutputImage(width, height);
  52. i8 = new OutputImage(width, height);
  53. i9 = new OutputImage(width, height);
  54. if (trackedFingers.Count >= 2)
  55. {
  56. this.edgeImage = edgeImage;
  57. this.outputImage = outputImage;
  58. // dst = (src > (MaxDepth - MinDepth)) ? 0 : 1
  59. handImage = depthImage.Image.ThresholdBinaryInv(new Gray(depthImage.MaxDepth - depthImage.MinDepth - 1), new Gray(1)).Convert<Gray, Byte>();
  60. fingers = getFingersWithoutThumb(trackedFingers);
  61. buildPointingHandMask();
  62. handImage = handImage.And(pointingHandMask);
  63. findLongestPalmContour();
  64. if (palmContour != null)
  65. {
  66. findConvexityDefectsSortedByDepth();
  67. removeConvexityDefectsCausedByFingers();
  68. findHandPoints();
  69. }
  70. }
  71. draw();
  72. }
  73. public void reset()
  74. {
  75. thumbDefectDepthFilter.reset();
  76. thumbDefectStartFilter.reset();
  77. thumbDefectEndFilter.reset();
  78. lastThumbDefectDepth = null;
  79. }
  80. private List<Finger> getFingersWithoutThumb(List<Finger> detectedFingers)
  81. {
  82. Finger leftMost = null;
  83. float minX = float.MaxValue;
  84. foreach (Finger f in detectedFingers)
  85. {
  86. float midX = ((f.Hand + f.Tip) / 2).X;
  87. if (midX < minX)
  88. {
  89. minX = midX;
  90. leftMost = f;
  91. }
  92. }
  93. List<Finger> result = new List<Finger>();
  94. foreach (Finger f in detectedFingers)
  95. {
  96. if (f != leftMost)
  97. result.Add(f);
  98. }
  99. return result;
  100. }
  101. private void fillFingerSlices(Image<Gray, Byte> image, byte val)
  102. {
  103. foreach (Finger f in fingers)
  104. {
  105. //foreach (FingerSlice s in f.SliceTrail.Slices)
  106. {
  107. image.Draw(new LineSegment2DF(f.SliceTrail.Slices[0].Start, f.SliceTrail.Slices[0].End), new Gray(val), 1);
  108. }
  109. }
  110. }
  111. private Finger getLongestFinger()
  112. {
  113. float maxLength = 0;
  114. Finger longest = null;
  115. foreach (Finger f in fingers)
  116. {
  117. if (f.LineSegment.Length > maxLength)
  118. {
  119. maxLength = f.LineSegment.Length;
  120. longest = f;
  121. }
  122. }
  123. return longest;
  124. }
  125. private Point getPointInPointingHand()
  126. {
  127. Finger finger = getLongestFinger();
  128. if (finger == null)
  129. return new Point(0, 0);
  130. Vector2D direction = (finger.Hand - finger.Tip).normalize();
  131. Vector2D pos = finger.Hand + direction;
  132. while (pos.isWithin(0, 0, width - 1, height - 1) && pointingHandMask.Data[pos.IntY, pos.IntX, 0] != 0)
  133. pos += direction;
  134. i3.fillCircle(pos.IntX, pos.IntY, 3, Color.Red);
  135. return pos;
  136. }
  137. public OutputImage i1, i2, i3, i4, i5, i6, i7, i8, i9;
  138. private void buildPointingHandMask()
  139. {
  140. pointingHandMask = new Image<Gray, byte>(width, height, new Gray(0));
  141. // dst = (src > 0) ? 1 : 0;
  142. pointingHandMask = pointingHandMask.Or(edgeImage.Image.ThresholdBinary(new Gray(0), new Gray(1)));
  143. i1.Image[0] = i1.Image[1] = i1.Image[2] = 255 * pointingHandMask;
  144. pointingHandMask = pointingHandMask.Dilate(2);
  145. i2.Image[0] = i2.Image[1] = i2.Image[2] = 255 * pointingHandMask;
  146. fillFingerSlices(pointingHandMask, 1);
  147. i3.Image[0] = i3.Image[1] = i3.Image[2] = 255 * pointingHandMask;
  148. //pointingHandMask = pointingHandMask.Dilate(1);
  149. //i4.Image[0] = i4.Image[1] = i4.Image[2] = 255 * pointingHandMask;
  150. MCvConnectedComp tmp = new MCvConnectedComp();
  151. // fill with value 2
  152. CvInvoke.cvFloodFill(pointingHandMask.Ptr, getPointInPointingHand(), new MCvScalar(2), new MCvScalar(0), new MCvScalar(0), out tmp, 0, IntPtr.Zero);
  153. // dst = (src > 1) ? 0 : 1 (src > 1 <-> src == 2 <-> src filled by flood fill)
  154. pointingHandMask = pointingHandMask.ThresholdBinaryInv(new Gray(1), new Gray(1));
  155. i5.Image[0] = i5.Image[1] = i5.Image[2] = 255 * pointingHandMask;
  156. pointingHandMask = pointingHandMask.Erode(6);
  157. i6.Image[0] = i6.Image[1] = i6.Image[2] = 255 * pointingHandMask;
  158. fillFingerSlices(pointingHandMask, 0);
  159. i7.Image[0] = i7.Image[1] = i7.Image[2] = 255 * pointingHandMask;
  160. pointingHandMask = pointingHandMask.Erode(2);
  161. i8.Image[0] = i8.Image[1] = i8.Image[2] = 255 * pointingHandMask;
  162. // only debug
  163. i9.Image[0] = i9.Image[1] = i9.Image[2] = 255 * handImage.And(pointingHandMask);
  164. }
  165. private void findLongestPalmContour()
  166. {
  167. Contour<Point> contour = handImage.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL);
  168. palmContour = contour;
  169. double maxPerimeter = 0;
  170. while (contour != null)
  171. {
  172. if (contour.Perimeter > maxPerimeter)
  173. {
  174. maxPerimeter = contour.Perimeter;
  175. palmContour = contour;
  176. }
  177. contour = contour.HNext;
  178. }
  179. }
  180. private void findConvexityDefectsSortedByDepth()
  181. {
  182. convexityDefects = new List<MCvConvexityDefect>(palmContour.GetConvexityDefacts(new MemStorage(), Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE));
  183. convexityDefects.Sort(delegate(MCvConvexityDefect d1, MCvConvexityDefect d2)
  184. {
  185. if (d1.Depth < d2.Depth)
  186. return 1;
  187. else if (d1.Depth > d2.Depth)
  188. return -1;
  189. return 0;
  190. });
  191. }
  192. private void removeConvexityDefectsCausedByFingers()
  193. {
  194. List<MCvConvexityDefect> newDefects = new List<MCvConvexityDefect>();
  195. foreach (MCvConvexityDefect d in convexityDefects)
  196. {
  197. bool remove = false;
  198. float minFingerLineDist = float.MaxValue;
  199. foreach (Finger f in fingers)
  200. {
  201. Utility.LineSegment2D defectLine = new Utility.LineSegment2D(new Vector2D(d.StartPoint), new Vector2D(d.EndPoint));
  202. Vector2D intersection = defectLine.Line.getIntersection(f.LineSegment.Line);
  203. if (intersection.isInBox(defectLine.P1, defectLine.P2) && intersection.isInBox(f.LineSegment.P1, f.LineSegment.P2))
  204. {
  205. remove = true;
  206. break;
  207. }
  208. Vector2D mid = (new Vector2D(d.StartPoint) + new Vector2D(d.EndPoint)) / 2.0f;
  209. float dist = f.LineSegment.getDistanceTo(mid);
  210. if (dist < minFingerLineDist)
  211. minFingerLineDist = dist;
  212. }
  213. if (minFingerLineDist >= Constants.PalmMinDefectMidFingerLineDistance && !remove)
  214. newDefects.Add(d);
  215. }
  216. convexityDefects = newDefects;
  217. }
  218. private MCvConvexityDefect? findThumbDefect()
  219. {
  220. foreach (MCvConvexityDefect d in convexityDefects)
  221. {
  222. Vector2D depth = new Vector2D(d.DepthPoint);
  223. Vector2D start = new Vector2D(d.StartPoint);
  224. Vector2D end = new Vector2D(d.EndPoint);
  225. float angle = (float) ((depth - start).getAngleBetween(depth - end) * 180 / Math.PI);
  226. if (angle <= Constants.PalmMaxThumbDefectAngle)
  227. {
  228. return d;
  229. }
  230. }
  231. return null;
  232. }
  233. private void findHandPoints()
  234. {
  235. MCvConvexityDefect? thumbDefect = findThumbDefect();
  236. if (convexityDefects.Count > 0 && (thumbDefect != null || thumbDefectDepthFilter.Initialized))
  237. {
  238. if (thumbDefect != null)
  239. {
  240. thumbDefectDepth = new Vector2D(thumbDefect.Value.DepthPoint);
  241. thumbDefectStart = new Vector2D(thumbDefect.Value.StartPoint);
  242. thumbDefectEnd = new Vector2D(thumbDefect.Value.EndPoint);
  243. }
  244. if (!thumbDefectDepthFilter.Initialized)
  245. {
  246. thumbDefectDepthFilter.setInitialPosition(thumbDefectDepth);
  247. thumbDefectStartFilter.setInitialPosition(thumbDefectStart);
  248. thumbDefectEndFilter.setInitialPosition(thumbDefectEnd);
  249. }
  250. else
  251. {
  252. thumbDefectDepth = thumbDefectDepthFilter.getCorrectedPosition(thumbDefectDepth);
  253. thumbDefectStart = thumbDefectStartFilter.getCorrectedPosition(thumbDefectStart);
  254. thumbDefectEnd = thumbDefectEndFilter.getCorrectedPosition(thumbDefectEnd);
  255. }
  256. lastThumbDefectDepth = thumbDefectDepth;
  257. Vector2D handLength, handWidth;
  258. if (thumbDefectDepth.getDistanceTo(thumbDefectStart) > thumbDefectDepth.getDistanceTo(thumbDefectEnd))
  259. {
  260. //right hand
  261. handLength = thumbDefectStart - thumbDefectDepth;
  262. handWidth = 0.8f * new Vector2D(-handLength.Y, handLength.X);
  263. topLeft = thumbDefectStart;
  264. bottomLeft = thumbDefectDepth - 0.4f * handLength;
  265. bottomRight = bottomLeft + handWidth;
  266. topRight = bottomRight + 1.2f * handLength - 0.3f * handWidth;
  267. }
  268. else
  269. {
  270. //left hand
  271. handLength = thumbDefectEnd - thumbDefectDepth;
  272. handWidth = 0.8f * new Vector2D(handLength.Y, -handLength.X);
  273. topRight = thumbDefectEnd;
  274. bottomRight = thumbDefectDepth - 0.4f * handLength;
  275. bottomLeft = bottomRight + handWidth;
  276. topLeft = bottomLeft + 1.2f * handLength - 0.3f * handWidth;
  277. }
  278. PalmQuad = new Quadrangle(bottomLeft, topLeft, topRight, bottomRight);
  279. }
  280. }
  281. private void draw()
  282. {
  283. if (palmContour != null && palmContour.Count<Point>() > 0) {
  284. outputImage.drawContour(palmContour, Constants.PalmConturColor);
  285. outputImage.drawPoints(palmContour.GetConvexHull(Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE), Constants.PalmConvexHullColor);
  286. }
  287. if (PalmQuad != null)
  288. {
  289. outputImage.fillCircle(thumbDefectStart.IntX, thumbDefectStart.IntY, 3, Color.Red);
  290. outputImage.fillCircle(thumbDefectEnd.IntX, thumbDefectEnd.IntY, 3, Color.Red);
  291. outputImage.fillCircle(thumbDefectDepth.IntX, thumbDefectDepth.IntY, 3, Color.Red);
  292. outputImage.drawLineSegment(new Utility.LineSegment2D(thumbDefectDepth, (thumbDefectStart + thumbDefectEnd) / 2.0f), Constants.PalmThumbDefectColor, 1);
  293. Vector2D[] vertices = PalmQuad.Vertices;
  294. for (int i = 0; i < 4; ++i)
  295. outputImage.drawLineSegment(new bbiwarg.Utility.LineSegment2D(vertices[i], vertices[(i + 1) % 4]), Constants.PalmQuadColor);
  296. drawGrid(new Vector2D(vertices[0]), new Vector2D(vertices[1]), new Vector2D(vertices[2]), new Vector2D(vertices[3]));
  297. }
  298. }
  299. private void drawGrid(Vector2D a, Vector2D b, Vector2D c, Vector2D d)
  300. {
  301. Vector2D relAB = (b - a) / Constants.PalmGridRows;
  302. Vector2D relDC = (c - d) / Constants.PalmGridRows;
  303. Vector2D relBC = (c - b) / Constants.PalmGridColumns;
  304. Vector2D relAD = (d - a) / Constants.PalmGridColumns;
  305. for (int i = 1; i < Constants.PalmGridRows; i++)
  306. {
  307. outputImage.drawLineSegment(new bbiwarg.Utility.LineSegment2D(a + i * relAB, d + i * relDC), Constants.PalmGridColor);
  308. }
  309. for (int i = 1; i < Constants.PalmGridColumns; i++)
  310. {
  311. outputImage.drawLineSegment(new bbiwarg.Utility.LineSegment2D(a + i * relAD, b + i * relBC), Constants.PalmGridColor);
  312. }
  313. }
  314. }
  315. }