Quadrangle.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 bbiwarg.Recognition.HandRecognition;
  8. using Emgu.CV;
  9. using Emgu.CV.Structure;
  10. namespace bbiwarg.Utility
  11. {
  12. class Quadrangle
  13. {
  14. public Vector2D[] Vertices { get { return new Vector2D[4] { BottomLeft, TopLeft, TopRight, BottomRight }; } }
  15. public Vector2D BottomLeft { get; private set; }
  16. public Vector2D TopLeft { get; private set; }
  17. public Vector2D TopRight { get; private set; }
  18. public Vector2D BottomRight { get; private set; }
  19. public float Area {get; private set;}
  20. public Image<Gray, Byte> Mask { get; private set; }
  21. public Quadrangle(Vector2D bottomLeft, Vector2D topLeft, Vector2D topRight, Vector2D bottomRight, int width, int height)
  22. {
  23. BottomLeft = bottomLeft;
  24. TopLeft = topLeft;
  25. TopRight = topRight;
  26. BottomRight = bottomRight;
  27. Contour<PointF> contourPoints = new Contour<PointF>(new MemStorage());
  28. contourPoints.Push(BottomLeft);
  29. contourPoints.Push(TopLeft);
  30. contourPoints.Push(TopRight);
  31. contourPoints.Push(BottomRight);
  32. Area = (float) contourPoints.Area;
  33. Mask = new Image<Gray, byte>(width, height);
  34. Point[] polyPoints = new Point[4];
  35. polyPoints[0] = BottomLeft;
  36. polyPoints[1] = TopLeft;
  37. polyPoints[2] = TopRight;
  38. polyPoints[3] = BottomRight;
  39. Mask.FillConvexPoly(polyPoints, new Gray(255));
  40. }
  41. public Vector2D getRelativePosition(Vector2D p, Hand.HandSide side)
  42. {
  43. Vector2D a, b, c, d;
  44. if (side == Hand.HandSide.Left)
  45. {
  46. a = BottomLeft;
  47. b = TopLeft;
  48. c = TopRight;
  49. d = BottomRight;
  50. }
  51. else
  52. {
  53. a = BottomRight;
  54. b = TopRight;
  55. c = TopLeft;
  56. d = BottomLeft;
  57. }
  58. float C = (a.Y - p.Y) * (d.X - p.X) - (a.X - p.X) * (d.Y - p.Y);
  59. float B = (a.Y - p.Y) * (c.X - d.X) + (b.Y - a.Y) * (d.X - p.X) - (a.X - p.X) * (c.Y - d.Y) - (b.X - a.X) * (d.Y - p.Y);
  60. float A = (b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y);
  61. float D = B * B - 4 * A * C;
  62. float u = (-B - (float)Math.Sqrt(D)) / (2 * A);
  63. float p1x = a.X + (b.X - a.X) * u;
  64. float p2x = d.X + (c.X - d.X) * u;
  65. float px = p.X;
  66. float v = (px - p1x) / (p2x - p1x);
  67. return new Vector2D(v, u);
  68. }
  69. }
  70. }