DepthImage.cs 2.4 KB

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