HandDetector.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. FingerSlice slice = finger.SliceTrail.Slices[1];
  41. image.Draw(new Emgu.CV.Structure.LineSegment2D(slice.Start, slice.End), new Gray(255), 2);
  42. }
  43. Hands = new List<Hand>();
  44. foreach (Finger finger in fingers)
  45. {
  46. bool newHand = true;
  47. foreach (Hand hand in Hands)
  48. {
  49. if (hand.isInside(finger.HandPoint))
  50. {
  51. hand.addFinger(finger);
  52. newHand = false;
  53. }
  54. }
  55. if (newHand)
  56. {
  57. Image<Gray, byte> mask = new Image<Gray, byte>(width + 2, height + 2);
  58. MCvConnectedComp comp = new MCvConnectedComp();
  59. 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);
  60. if (comp.area < maxArea * Constants.HandMaxSize)
  61. {
  62. Hand hand = new Hand(mask.Copy(new Rectangle(1, 1, width, height)));
  63. hand.addFinger(finger);
  64. Hands.Add(hand);
  65. }
  66. }
  67. }
  68. }
  69. private void drawHands() {
  70. int maxIndex = Math.Min(3, Hands.Count);
  71. for (int i = 0; i < maxIndex ; i++)
  72. {
  73. outputImage.Image[i] = Hands[i].Mask.Mul(255);
  74. }
  75. }
  76. }
  77. }