DepthImage.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using MathNet.Numerics.LinearAlgebra.Single;
  7. using System.Drawing;
  8. using Emgu.CV;
  9. using Emgu.CV.Structure;
  10. namespace bbiwarg.DataSource
  11. {
  12. /**
  13. * Represents an depth image where the depth is given in distance to the camera in millimeters.
  14. */
  15. class DepthImage
  16. {
  17. private int width, height;
  18. private Image<Gray, Int16> image;
  19. public DepthImage(int width, int height, short[] data)
  20. {
  21. this.width = width;
  22. this.height = height;
  23. image = new Image<Gray, Int16>(width, height);
  24. for (int i = 0; i < data.Length; ++i)
  25. setDepth(i % width, i / width, data[i]);
  26. }
  27. public int getWidth()
  28. {
  29. return width;
  30. }
  31. public int getHeight()
  32. {
  33. return height;
  34. }
  35. public short getDepth(int x, int y)
  36. {
  37. return image.Data[y, x, 0];
  38. }
  39. private void setDepth(int x, int y, short depth)
  40. {
  41. image.Data[y, x, 0] = depth;
  42. }
  43. public void filterMedian(int filterSize)
  44. {
  45. image = image.SmoothMedian(3);
  46. }
  47. public void thresholdDepth(int min, int max)
  48. {
  49. image = image.ThresholdToZero(new Gray(min));
  50. image = image.ThresholdBinaryInv(new Gray(max), new Gray(2000));
  51. }
  52. public void thresholdPosition(int minX, int maxX, int minY, int maxY)
  53. {
  54. for (int x = 0; x < width; ++x)
  55. {
  56. for (int y = 0; y < height; ++y)
  57. {
  58. if (x < minX || x > maxX || y < minY || y > maxY)
  59. setDepth(x, y, 0);
  60. }
  61. }
  62. }
  63. public List<Vector> getRectPoints()
  64. {
  65. Image<Gray, Byte> tmp = image.Convert<Byte>(delegate(short s) { return (s == 2000) ? (byte) 1 : (byte) 0; });
  66. Contour<Point> contours = tmp.FindContours();
  67. MCvBox2D box = contours.GetMinAreaRect();
  68. Seq<Point> points = contours.GetConvexHull(Emgu.CV.CvEnum.ORIENTATION.CV_CLOCKWISE);
  69. List<Vector> result = new List<Vector>();
  70. foreach (Point p in points)
  71. {
  72. result.Add(new DenseVector(new float[]{p.X, p.Y}));
  73. }
  74. return result;
  75. }
  76. }
  77. }