Quadrangle.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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)
  42. {
  43. Vector2D a, b, c, d;
  44. a = BottomLeft;
  45. b = TopLeft;
  46. c = TopRight;
  47. d = BottomRight;
  48. float C = (a.Y - p.Y) * (d.X - p.X) - (a.X - p.X) * (d.Y - p.Y);
  49. 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);
  50. float A = (b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y);
  51. float D = B * B - 4 * A * C;
  52. float u = (-B - (float)Math.Sqrt(D)) / (2 * A);
  53. float p1x = a.X + (b.X - a.X) * u;
  54. float p2x = d.X + (c.X - d.X) * u;
  55. float px = p.X;
  56. float v = (px - p1x) / (p2x - p1x);
  57. return new Vector2D(u, v);
  58. }
  59. public bool isInside(Vector2D point)
  60. {
  61. Vector2D relativePos = getRelativePosition(point);
  62. return (relativePos.X >= 0 && relativePos.X <= 1.0 && relativePos.Y >= 0 && relativePos.Y <= 1.0);
  63. }
  64. }
  65. }