Projection2DTo2D.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Drawing;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Emgu.CV;
  8. using Emgu.CV.Structure;
  9. namespace bbiwarg.Utility
  10. {
  11. class Projection2DTo2D
  12. {
  13. private ImageSize sizeA;
  14. private ImageSize sizeB;
  15. private List<PointF> calibrationPointsA;
  16. private List<PointF> calibrationPointsB;
  17. private int numPointsForCalibration;
  18. private HomographyMatrix homography;
  19. public bool IsCalibrated { get; private set; }
  20. public Projection2DTo2D(ImageSize sizeA, ImageSize sizeB, int numPointsForCalibration = 4) {
  21. this.sizeA = sizeA;
  22. this.sizeB = sizeB;
  23. this.numPointsForCalibration = numPointsForCalibration;
  24. reset();
  25. }
  26. public void reset() {
  27. homography = null;
  28. IsCalibrated = false;
  29. calibrationPointsA = new List<PointF>();
  30. calibrationPointsB = new List<PointF>();
  31. }
  32. public void addCalibrationPoints(Vector2D pointA, Vector2D pointB) {
  33. calibrationPointsA.Add(sizeA.getRelativePoint(pointA));
  34. calibrationPointsB.Add(sizeB.getRelativePoint(pointB));
  35. if (calibrationPointsA.Count == numPointsForCalibration)
  36. calibrate();
  37. }
  38. public Vector2D projectPoint(Vector2D pointA) {
  39. PointF[] pointfsB = new PointF[1] {sizeA.getRelativePoint(pointA)};
  40. homography.ProjectPoints(pointfsB);
  41. return sizeB.getAbsolutePoint(new Vector2D(pointfsB[0]));
  42. }
  43. private void calibrate() {
  44. homography = CameraCalibration.FindHomography(calibrationPointsA.ToArray(), calibrationPointsB.ToArray(), Emgu.CV.CvEnum.HOMOGRAPHY_METHOD.DEFAULT, 0.995);
  45. calibrationPointsA.Clear();
  46. calibrationPointsB.Clear();
  47. IsCalibrated = true;
  48. exportHomography();
  49. }
  50. private void exportHomography() {
  51. String[] fileData = new String[homography.Size.Height];
  52. StringBuilder sb = new StringBuilder();
  53. for (int r = 0; r < homography.Size.Height; r++)
  54. {
  55. for (int c = 0; c < homography.Size.Width; c++)
  56. {
  57. sb.Append(homography.Data[r, c]);
  58. sb.Append(" ");
  59. }
  60. fileData[r] = sb.ToString();
  61. sb.Clear();
  62. }
  63. System.IO.File.WriteAllLines(Parameters.HomographyFileName, fileData);
  64. }
  65. }
  66. }