HandDetector.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using bbiwarg.Images;
  8. using bbiwarg.Detectors.FingerDetection;
  9. using bbiwarg.Graphics;
  10. using bbiwarg.Utility;
  11. using Emgu.CV;
  12. using Emgu.CV.Structure;
  13. namespace bbiwarg.Detectors.HandDetection
  14. {
  15. class HandDetector
  16. {
  17. private DepthImage depthImage;
  18. private EdgeImage edgeImage;
  19. private List<Finger> fingers;
  20. public List<Hand> Hands { get; private set; }
  21. public OutputImage outputImage;
  22. public HandDetector(DepthImage depthImage, EdgeImage edgeImage, List<Finger> fingers, OutputImage outputImage)
  23. {
  24. this.depthImage = depthImage;
  25. this.edgeImage = edgeImage;
  26. this.fingers = fingers;
  27. this.outputImage = outputImage;
  28. detectHands();
  29. drawHands();
  30. }
  31. private void detectHands()
  32. {
  33. int width = depthImage.Width;
  34. int height = depthImage.Height;
  35. int maxArea = width * height;
  36. Image<Gray, byte> image = edgeImage.Image.Copy().Dilate(2).Erode(2).Mul(255);
  37. //draw top finger slice
  38. foreach (Finger finger in fingers)
  39. {
  40. // TODO: connect contour with other edges
  41. //Contour<Point> contour = finger.getContour();
  42. //image.FillConvexPoly(contour.ToArray(), new Gray(0));
  43. //image.DrawPolyline(finger.getContour().ToArray(), false, new Gray(255), 1);
  44. FingerSlice slice = finger.SliceTrail.Slices[1];
  45. image.Draw(new Emgu.CV.Structure.LineSegment2D(slice.Start, slice.End), new Gray(255), 2);
  46. }
  47. Hands = new List<Hand>();
  48. foreach (Finger finger in fingers)
  49. {
  50. bool newHand = true;
  51. foreach (Hand hand in Hands)
  52. {
  53. if (hand.isInside(finger.HandPoint))
  54. {
  55. hand.addFinger(finger);
  56. newHand = false;
  57. }
  58. }
  59. if (newHand)
  60. {
  61. Image<Gray, byte> mask = new Image<Gray, byte>(width + 2, height + 2);
  62. MCvConnectedComp comp = new MCvConnectedComp();
  63. CvInvoke.cvFloodFill(image, finger.HandPoint, new MCvScalar(255), new MCvScalar(1), new MCvScalar(1), out comp, Emgu.CV.CvEnum.CONNECTIVITY.FOUR_CONNECTED, Emgu.CV.CvEnum.FLOODFILL_FLAG.DEFAULT, mask);
  64. if (comp.area < maxArea * Constants.HandMaxSize)
  65. {
  66. Hand hand = new Hand(mask.Copy(new Rectangle(1, 1, width, height)));
  67. hand.addFinger(finger);
  68. Hands.Add(hand);
  69. }
  70. }
  71. }
  72. }
  73. private void drawHands() {
  74. int maxIndex = Math.Min(3, Hands.Count);
  75. for (int i = 0; i < maxIndex ; i++)
  76. {
  77. outputImage.Image[i] = Hands[i].Mask.Mul(255);
  78. }
  79. }
  80. }
  81. }