PalmDetector.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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.HandPoint + f.TipPoint) / 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 fillFirstFingerSlices(Image<Gray, Byte> image, byte val)
  102. {
  103. foreach (Finger f in fingers)
  104. {
  105. image.Draw(new LineSegment2DF(f.SliceTrail.Slices[0].Start, f.SliceTrail.Slices[0].End), new Gray(val), 1);
  106. }
  107. }
  108. private Point getPointInPointingHand()
  109. {
  110. Finger finger = fingers[0];
  111. if (finger == null)
  112. return new Point(0, 0);
  113. Vector2D direction = (finger.HandPoint - finger.TipPoint).normalize();
  114. Vector2D pos = finger.HandPoint + direction;
  115. while (pos.isWithin(0, 0, width - 1, height - 1) && pointingHandMask.Data[pos.IntY, pos.IntX, 0] != 0)
  116. pos += direction;
  117. i3.fillCircle(pos.IntX, pos.IntY, 3, Color.Red);
  118. return pos;
  119. }
  120. public OutputImage i1, i2, i3, i4, i5, i6, i7, i8, i9;
  121. private void buildPointingHandMask()
  122. {
  123. pointingHandMask = new Image<Gray, byte>(width, height, new Gray(0));
  124. // dst = (src > 0) ? 1 : 0;
  125. pointingHandMask = pointingHandMask.Or(edgeImage.Image);
  126. i1.Image[0] = i1.Image[1] = i1.Image[2] = 255 * pointingHandMask;
  127. pointingHandMask = pointingHandMask.Dilate(1);
  128. i2.Image[0] = i2.Image[1] = i2.Image[2] = 255 * pointingHandMask;
  129. fillFirstFingerSlices(pointingHandMask, 1);
  130. i3.Image[0] = i3.Image[1] = i3.Image[2] = 255 * pointingHandMask;
  131. //pointingHandMask = pointingHandMask.Dilate(1);
  132. //i4.Image[0] = i4.Image[1] = i4.Image[2] = 255 * pointingHandMask;
  133. MCvConnectedComp tmp = new MCvConnectedComp();
  134. // fill with value 2
  135. CvInvoke.cvFloodFill(pointingHandMask.Ptr, getPointInPointingHand(), new MCvScalar(2), new MCvScalar(0), new MCvScalar(0), out tmp, 0, IntPtr.Zero);
  136. // dst = (src > 1) ? 0 : 1 (src > 1 <-> src == 2 <-> src filled by flood fill)
  137. pointingHandMask = pointingHandMask.ThresholdBinaryInv(new Gray(1), new Gray(1));
  138. i5.Image[0] = i5.Image[1] = i5.Image[2] = 255 * pointingHandMask;
  139. pointingHandMask = pointingHandMask.Erode(6);
  140. i6.Image[0] = i6.Image[1] = i6.Image[2] = 255 * pointingHandMask;
  141. fillFirstFingerSlices(pointingHandMask, 0);
  142. i7.Image[0] = i7.Image[1] = i7.Image[2] = 255 * pointingHandMask;
  143. pointingHandMask = pointingHandMask.Erode(2);
  144. i8.Image[0] = i8.Image[1] = i8.Image[2] = 255 * pointingHandMask;
  145. // only debug
  146. i9.Image[0] = i9.Image[1] = i9.Image[2] = 255 * handImage.And(pointingHandMask);
  147. }
  148. private void findLongestPalmContour()
  149. {
  150. Contour<Point> contour = handImage.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_EXTERNAL);
  151. palmContour = contour;
  152. double maxPerimeter = 0;
  153. while (contour != null)
  154. {
  155. if (contour.Perimeter > maxPerimeter)
  156. {
  157. maxPerimeter = contour.Perimeter;
  158. palmContour = contour;
  159. }
  160. contour = contour.HNext;
  161. }
  162. }
  163. private void findConvexityDefectsSortedByDepth()
  164. {
  165. convexityDefects = new List<MCvConvexityDefect>(palmContour.GetConvexityDefacts(new MemStorage(), Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE));
  166. convexityDefects.Sort(delegate(MCvConvexityDefect d1, MCvConvexityDefect d2)
  167. {
  168. if (d1.Depth < d2.Depth)
  169. return 1;
  170. else if (d1.Depth > d2.Depth)
  171. return -1;
  172. return 0;
  173. });
  174. }
  175. private void removeConvexityDefectsCausedByFingers()
  176. {
  177. List<MCvConvexityDefect> newDefects = new List<MCvConvexityDefect>();
  178. foreach (MCvConvexityDefect d in convexityDefects)
  179. {
  180. bool fingerIntersectsStartEnd = false;
  181. float minFingerLineDist = float.MaxValue;
  182. foreach (Finger f in fingers)
  183. {
  184. Utility.LineSegment2D defectLine = new Utility.LineSegment2D(new Vector2D(d.StartPoint), new Vector2D(d.EndPoint));
  185. Vector2D intersection = defectLine.Line.getIntersection(f.LineSegment.Line);
  186. if (intersection != null &&
  187. intersection.isInBox(defectLine.P1, defectLine.P2) && intersection.isInBox(f.LineSegment.P1, f.LineSegment.P2))
  188. {
  189. fingerIntersectsStartEnd = true;
  190. break;
  191. }
  192. Vector2D mid = (new Vector2D(d.StartPoint) + new Vector2D(d.EndPoint)) / 2.0f;
  193. float dist = f.LineSegment.getDistanceTo(mid);
  194. if (dist < minFingerLineDist)
  195. minFingerLineDist = dist;
  196. }
  197. if (minFingerLineDist >= Constants.PalmMinDefectMidFingerLineDistance && !fingerIntersectsStartEnd)
  198. newDefects.Add(d);
  199. }
  200. convexityDefects = newDefects;
  201. }
  202. private int i = 0;
  203. private MCvConvexityDefect? findThumbDefect()
  204. {
  205. foreach (MCvConvexityDefect d in convexityDefects)
  206. {
  207. Vector2D depth = new Vector2D(d.DepthPoint);
  208. Vector2D start = new Vector2D(d.StartPoint);
  209. Vector2D end = new Vector2D(d.EndPoint);
  210. float l1 = (depth - start).Length;
  211. float l2 = (depth - end).Length;
  212. float lengthQuotient = Math.Max(l1, l2) / Math.Min(l1, l2);
  213. float angle = (float) ((depth - start).getAngleBetween(depth - end) * 180 / Math.PI);
  214. if (angle <= Constants.PalmMaxThumbDefectAngle &&
  215. lengthQuotient >= Constants.PalmMinThumbDefectLengthQuotient && lengthQuotient <= Constants.PalmMaxThumbDefectLengthQuotient)
  216. {
  217. return d;
  218. }
  219. }
  220. //Console.WriteLine("no palm defect found (" + i + ")");
  221. foreach (MCvConvexityDefect d in convexityDefects)
  222. {
  223. Vector2D depth = new Vector2D(d.DepthPoint);
  224. Vector2D start = new Vector2D(d.StartPoint);
  225. Vector2D end = new Vector2D(d.EndPoint);
  226. float l1 = (depth - start).Length;
  227. float l2 = (depth - end).Length;
  228. float lengthQuotient = Math.Max(l1, l2) / Math.Min(l1, l2);
  229. float angle = (float)((depth - start).getAngleBetween(depth - end) * 180 / Math.PI);
  230. //Console.WriteLine("angle: " + angle + " quotient: " + lengthQuotient);
  231. }
  232. ++i;
  233. return null;
  234. }
  235. private void findHandPoints()
  236. {
  237. MCvConvexityDefect? thumbDefect = findThumbDefect();
  238. if (convexityDefects.Count > 0 && (thumbDefect != null || thumbDefectDepthFilter.Initialized))
  239. {
  240. if (thumbDefect != null)
  241. {
  242. thumbDefectDepth = new Vector2D(thumbDefect.Value.DepthPoint);
  243. thumbDefectStart = new Vector2D(thumbDefect.Value.StartPoint);
  244. thumbDefectEnd = new Vector2D(thumbDefect.Value.EndPoint);
  245. }
  246. if (!thumbDefectDepthFilter.Initialized)
  247. {
  248. thumbDefectDepthFilter.setInitialPosition(thumbDefectDepth);
  249. thumbDefectStartFilter.setInitialPosition(thumbDefectStart);
  250. thumbDefectEndFilter.setInitialPosition(thumbDefectEnd);
  251. }
  252. else
  253. {
  254. thumbDefectDepth = thumbDefectDepthFilter.getCorrectedPosition(thumbDefectDepth);
  255. thumbDefectStart = thumbDefectStartFilter.getCorrectedPosition(thumbDefectStart);
  256. thumbDefectEnd = thumbDefectEndFilter.getCorrectedPosition(thumbDefectEnd);
  257. }
  258. lastThumbDefectDepth = thumbDefectDepth;
  259. Vector2D handLength, handWidth;
  260. if (thumbDefectDepth.getDistanceTo(thumbDefectStart) > thumbDefectDepth.getDistanceTo(thumbDefectEnd))
  261. {
  262. //right hand
  263. handLength = thumbDefectStart - thumbDefectDepth;
  264. handWidth = 0.85f * new Vector2D(-handLength.Y, handLength.X);
  265. topLeft = thumbDefectStart+0.15f*handLength;
  266. bottomLeft = thumbDefectDepth - 0.4f * handLength;
  267. bottomRight = bottomLeft + handWidth;
  268. topRight = bottomRight + 1.2f * handLength - 0.3f * handWidth;
  269. }
  270. else
  271. {
  272. //left hand
  273. handLength = thumbDefectEnd - thumbDefectDepth;
  274. handWidth = 0.85f * new Vector2D(handLength.Y, -handLength.X);
  275. topRight = thumbDefectEnd+0.15f*handLength;
  276. bottomRight = thumbDefectDepth - 0.4f * handLength;
  277. bottomLeft = bottomRight + handWidth;
  278. topLeft = bottomLeft + 1.15f * handLength - 0.35f * handWidth;
  279. }
  280. PalmQuad = new Quadrangle(bottomLeft, topLeft, topRight, bottomRight);
  281. }
  282. }
  283. private void draw()
  284. {
  285. if (palmContour != null && palmContour.Count<Point>() > 0) {
  286. outputImage.drawContour(palmContour, Constants.PalmConturColor);
  287. outputImage.drawPoints(palmContour.GetConvexHull(Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE), Constants.PalmConvexHullColor);
  288. }
  289. if (PalmQuad != null)
  290. {
  291. outputImage.fillCircle(thumbDefectStart.IntX, thumbDefectStart.IntY, 3, Color.Red);
  292. outputImage.fillCircle(thumbDefectEnd.IntX, thumbDefectEnd.IntY, 3, Color.Red);
  293. outputImage.fillCircle(thumbDefectDepth.IntX, thumbDefectDepth.IntY, 3, Color.Red);
  294. outputImage.drawLineSegment(new Utility.LineSegment2D(thumbDefectDepth, (thumbDefectStart + thumbDefectEnd) / 2.0f), Constants.PalmThumbDefectColor, 1);
  295. Vector2D[] vertices = PalmQuad.Vertices;
  296. for (int i = 0; i < 4; ++i)
  297. outputImage.drawLineSegment(new bbiwarg.Utility.LineSegment2D(vertices[i], vertices[(i + 1) % 4]), Constants.PalmQuadColor);
  298. drawGrid(new Vector2D(vertices[0]), new Vector2D(vertices[1]), new Vector2D(vertices[2]), new Vector2D(vertices[3]));
  299. }
  300. }
  301. private void drawGrid(Vector2D a, Vector2D b, Vector2D c, Vector2D d)
  302. {
  303. Vector2D relAB = (b - a) / Constants.PalmGridRows;
  304. Vector2D relDC = (c - d) / Constants.PalmGridRows;
  305. Vector2D relBC = (c - b) / Constants.PalmGridColumns;
  306. Vector2D relAD = (d - a) / Constants.PalmGridColumns;
  307. for (int i = 1; i < Constants.PalmGridRows; i++)
  308. {
  309. outputImage.drawLineSegment(new bbiwarg.Utility.LineSegment2D(a + i * relAB, d + i * relDC), Constants.PalmGridColor);
  310. }
  311. for (int i = 1; i < Constants.PalmGridColumns; i++)
  312. {
  313. outputImage.drawLineSegment(new bbiwarg.Utility.LineSegment2D(a + i * relAD, b + i * relBC), Constants.PalmGridColor);
  314. }
  315. }
  316. }
  317. }