PalmDetector.cs 14 KB

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