123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- using Emgu.CV;
- using Emgu.CV.Structure;
- using System.Drawing;
- namespace WingAIDiagnosisService.Carotid
- {
- public struct ResampleInitResult
- {
- public ImageEdge Edge;
- public ResampleErrorCode ErrorCode;
- public Size ResizeSize;
- }
- public class ImageEdge
- {
- private int _imageWidth;
- public int Left { get; set; }
- public int Right { get; set; }
- public int Height { get; }
- public int Width
- {
- get
- {
- return IsValid ? Right - Left + 1: _imageWidth;
- }
- }
- public bool IsValid
- {
- get
- {
- return Right > Left && Right - Left > 200;
- }
- }
- public ImageEdge(int width, int height)
- {
- Left = 0;
- Right = width - 1;
- Height = height;
- _imageWidth = width;
- }
- }
- public class ImageEdgeDetector
- {
- public static ImageEdge DetectImageEdge(Mat mat)
- {
- ImageEdge edge = new ImageEdge(mat.Width, mat.Height);
- using (var img = new Image<Gray, byte>(mat.Width, mat.Height))
- {
- CvInvoke.Threshold(mat, img, 20, 255, Emgu.CV.CvEnum.ThresholdType.Binary);
- edge.Left = FindLeft(img);
- edge.Right = FindRight(img);
- edge.Left = edge.Left - 4 <= 0 ? 0 : edge.Left - 4;
- edge.Right = edge.Right + 4 >= mat.Width - 1 ? mat.Width - 1 : edge.Right + 4;
- AdjustEdge(edge);
- //reset if not valid
- if (!edge.IsValid)
- {
- edge.Left = 0;
- edge.Right = mat.Width - 1;
- }
- }
- return edge;
- }
- private static int FindLeft(Image<Gray, byte> img)
- {
- for (int col = 0; col < img.Cols; ++col)
- {
- for (int row = 0; row < img.Rows; ++row)
- {
- if (img.Data[row, col, 0] == 255)
- {
- return col;
- }
- }
- }
- return 0;
- }
- private static int FindRight(Image<Gray, byte> img)
- {
- for (int col = img.Cols - 1; col > 0; --col)
- {
- for (int row = 0; row < img.Rows; ++row)
- {
- if (img.Data[row, col, 0] == 255)
- {
- return col;
- }
- }
- }
- return img.Cols - 1;
- }
- public static void AdjustEdge(ImageEdge edge)
- {
- var offset = edge.Width % 4;
- if (offset == 0)
- {
- return;
- }
- else
- {
- edge.Right -= offset;
- }
- }
- }
- }
|