c#检测图像中的矩形

时间:2011-05-10 04:25:20

标签: c# image image-processing

我想在下图中检测并获取一个Rects数组,每个矩形一个。我怎么能在c#中这样做?

基本上我正在尝试扫描屏幕拍摄的图像并解析窗口数组。

Rect是某种形式的(xloc,yloc,xsize,ysize) 返回的数组:rectangles = ParseRects(image);

Image

2 个答案:

答案 0 :(得分:23)

您最好的选择是使用AForge.Net library

以下代码源自ShapeChecker类的文档,您可能需要查看文档以进一步熟悉自己。

static void Main(string[] args)
{
    // Open your image
    string path = "test.png";
    Bitmap image = (Bitmap)Bitmap.FromFile(path);

    // locating objects
    BlobCounter blobCounter = new BlobCounter();

    blobCounter.FilterBlobs = true;
    blobCounter.MinHeight = 5;
    blobCounter.MinWidth = 5;

    blobCounter.ProcessImage(image);
    Blob[] blobs = blobCounter.GetObjectsInformation();

    // check for rectangles
    SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

    foreach (var blob in blobs)
    {
        List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blob);
        List<IntPoint> cornerPoints;

        // use the shape checker to extract the corner points
        if (shapeChecker.IsQuadrilateral(edgePoints, out cornerPoints))
        {
            // only do things if the corners form a rectangle
            if (shapeChecker.CheckPolygonSubType(cornerPoints) == PolygonSubType.Rectangle)
            {
                // here i use the graphics class to draw an overlay, but you
                // could also just use the cornerPoints list to calculate your
                // x, y, width, height values.
                List<Point> Points = new List<Point>();
                foreach (var point in cornerPoints)
                {
                    Points.Add(new Point(point.X, point.Y));
                }

                Graphics g = Graphics.FromImage(image);
                g.DrawPolygon(new Pen(Color.Red, 5.0f), Points.ToArray());

                image.Save("result.png");
            }
        }
    }
}

原始输入: original input

结果图片:enter image description here

答案 1 :(得分:0)

您可以看到行通过霍夫变换检测 和角落检测。 一些算法可能已经在C#中实现了