DepthImage.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 Emgu.CV;
  8. using Emgu.CV.Structure;
  9. namespace bbiwarg.Images
  10. {
  11. class DepthImage
  12. {
  13. public Image<Gray, byte> Image { get; private set; }
  14. public int Width { get; private set; }
  15. public int Height { get; private set; }
  16. public Int16 MinDepth { get; private set; }
  17. public Int16 MaxDepth { get; private set; }
  18. public DepthImage(Image<Gray, Int16> image)
  19. {
  20. Width = image.Width;
  21. Height = image.Height;
  22. //threshold min&maxDepth
  23. MinDepth = findMinDepth(image);
  24. MaxDepth = (Int16)(MinDepth + 200); // max = minDepth+255 (else it can't fit whole range in byte image)
  25. //smooth+threshold (dst = (src > (MaxDepth - MinDepth)) ? MaxDepth - MinDepth : src)
  26. Image = image.SmoothMedian(3).Sub(new Gray(MinDepth)).ThresholdTrunc(new Gray(MaxDepth - MinDepth)).Convert<Gray, byte>();
  27. }
  28. public Int16 getDepthAt(Point point)
  29. {
  30. return getDepthAt(point.X, point.Y);
  31. }
  32. public Int16 getDepthAt(int x, int y)
  33. {
  34. return (Int16)(MinDepth + Image.Data[y, x, 0]);
  35. }
  36. public void setDepthAt(Point point, Int16 depth)
  37. {
  38. setDepthAt(point.X, point.Y, depth);
  39. }
  40. public void setDepthAt(int x, int y, Int16 depth)
  41. {
  42. Image.Data[y, x, 0] = (byte)(depth - MinDepth);
  43. }
  44. public float getRelativeDepthAt(Point point)
  45. {
  46. return getRelativeDepthAt(point.X, point.Y);
  47. }
  48. public float getRelativeDepthAt(int x, int y)
  49. {
  50. float minMaxInterval = Math.Max(MaxDepth - MinDepth, 1);
  51. return (getDepthAt(x, y) - MinDepth) / minMaxInterval;
  52. }
  53. private Int16 findMinDepth(Image<Gray, Int16> image)
  54. {
  55. // min and max values
  56. double[] min, max;
  57. // min and max locations
  58. Point[] minLoc, maxLoc;
  59. image.MinMax(out min, out max, out minLoc, out maxLoc);
  60. return (Int16)min[0];
  61. }
  62. }
  63. }