ImageEdgeDetector.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using Emgu.CV;
  2. using Emgu.CV.Structure;
  3. using System.Drawing;
  4. namespace WingAIDiagnosisService.Carotid
  5. {
  6. public struct ResampleInitResult
  7. {
  8. public ImageEdge Edge;
  9. public ResampleErrorCode ErrorCode;
  10. public Size ResizeSize;
  11. }
  12. public class ImageEdge
  13. {
  14. private int _imageWidth;
  15. public int Left { get; set; }
  16. public int Right { get; set; }
  17. public int Height { get; }
  18. public int Width
  19. {
  20. get
  21. {
  22. return IsValid ? Right - Left + 1: _imageWidth;
  23. }
  24. }
  25. public bool IsValid
  26. {
  27. get
  28. {
  29. return Right > Left && Right - Left > 200;
  30. }
  31. }
  32. public ImageEdge(int width, int height)
  33. {
  34. Left = 0;
  35. Right = width - 1;
  36. Height = height;
  37. _imageWidth = width;
  38. }
  39. }
  40. public class ImageEdgeDetector
  41. {
  42. public static ImageEdge DetectImageEdge(Mat mat)
  43. {
  44. ImageEdge edge = new ImageEdge(mat.Width, mat.Height);
  45. using (var img = new Image<Gray, byte>(mat.Width, mat.Height))
  46. {
  47. CvInvoke.Threshold(mat, img, 20, 255, Emgu.CV.CvEnum.ThresholdType.Binary);
  48. edge.Left = FindLeft(img);
  49. edge.Right = FindRight(img);
  50. edge.Left = edge.Left - 4 <= 0 ? 0 : edge.Left - 4;
  51. edge.Right = edge.Right + 4 >= mat.Width - 1 ? mat.Width - 1 : edge.Right + 4;
  52. AdjustEdge(edge);
  53. //reset if not valid
  54. if (!edge.IsValid)
  55. {
  56. edge.Left = 0;
  57. edge.Right = mat.Width - 1;
  58. }
  59. }
  60. return edge;
  61. }
  62. private static int FindLeft(Image<Gray, byte> img)
  63. {
  64. for (int col = 0; col < img.Cols; ++col)
  65. {
  66. for (int row = 0; row < img.Rows; ++row)
  67. {
  68. if (img.Data[row, col, 0] == 255)
  69. {
  70. return col;
  71. }
  72. }
  73. }
  74. return 0;
  75. }
  76. private static int FindRight(Image<Gray, byte> img)
  77. {
  78. for (int col = img.Cols - 1; col > 0; --col)
  79. {
  80. for (int row = 0; row < img.Rows; ++row)
  81. {
  82. if (img.Data[row, col, 0] == 255)
  83. {
  84. return col;
  85. }
  86. }
  87. }
  88. return img.Cols - 1;
  89. }
  90. public static void AdjustEdge(ImageEdge edge)
  91. {
  92. var offset = edge.Width % 4;
  93. if (offset == 0)
  94. {
  95. return;
  96. }
  97. else
  98. {
  99. edge.Right -= offset;
  100. }
  101. }
  102. }
  103. }