HandDetector.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  30. private void detectHands()
  31. {
  32. int width = depthImage.Width;
  33. int height = depthImage.Height;
  34. int maxArea = width * height;
  35. Image<Gray, byte> image = edgeImage.Image.Copy().Dilate(2).Erode(2).Mul(255);
  36. //draw top finger slice
  37. foreach (Finger finger in fingers)
  38. {
  39. FingerSlice slice = finger.SliceTrail.Start;
  40. image.Draw(new Emgu.CV.Structure.LineSegment2D(slice.Start, slice.End), new Gray(255), 1);
  41. }
  42. Hands = new List<Hand>();
  43. foreach (Finger finger in fingers)
  44. {
  45. bool newHand = true;
  46. foreach (Hand hand in Hands)
  47. {
  48. if (hand.isInside(finger.HandPoint))
  49. {
  50. hand.addFinger(finger);
  51. newHand = false;
  52. }
  53. }
  54. if (newHand)
  55. {
  56. Image<Gray, byte> mask = new Image<Gray, byte>(width + 2, height + 2);
  57. MCvConnectedComp comp = new MCvConnectedComp();
  58. 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);
  59. if (comp.area < maxArea * Constants.HandMaxSize)
  60. {
  61. Hand hand = new Hand(mask.Copy(new Rectangle(1, 1, width, height)));
  62. hand.addFinger(finger);
  63. Hands.Add(hand);
  64. }
  65. }
  66. }
  67. for (int i = 0; i < Math.Min(3, Hands.Count); i++)
  68. {
  69. outputImage.Image[i] = Hands[i].Mask.Mul(255);
  70. }
  71. }
  72. }
  73. }