使用AForge c#进行物体检测

时间:2017-01-24 14:11:28

标签: c# aforge

我正在尝试使用AForge.NET在C#windows form Project中创建对象检测。

我写了这段代码:

public void DetectCorners()
{
    // Load image and create everything you need for drawing
    Bitmap image = new Bitmap(@"C:\Users\ssammour\Desktop\Unbenannt.PNG");
    originalPicture.ImageLocation = @"C:\Users\ssammour\Desktop\Unbenannt.PNG";
    BlobCounter blobCounter = new BlobCounter();
    blobCounter.ProcessImage(image);
    Graphics g = this.CreateGraphics();
    Blob[] blobs = blobCounter.GetObjectsInformation();
    SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
    Pen redPen = new Pen(Color.Red);
    for (int i = 0, n = blobs.Length; i < n; i++)
    {
        List<IntPoint> corners;
        List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

        if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
        {
            g.DrawPolygon(redPen, ToPointsArray(corners));
            image = new Bitmap(image.Width, image.Height, g);
        }
    }

    // Display
    newPicture.Image = image;
}

private System.Drawing.Point[] ToPointsArray(List<IntPoint> points)
{
    System.Drawing.Point[] array = new System.Drawing.Point[points.Count];
    return array;
}

结果总是黑色照片,我不知道为什么。 我用这张照片来试试代码: enter image description here

但仍会收到一张黑色照片。 任何帮助?那为什么呢? 如果你愿意,可以告诉我如何检测图像中的所有物体。

1 个答案:

答案 0 :(得分:4)

您在ToPointsArray中没有做任何事情。你只是返回一个相同长度的数组。

你应该做这样的事情(我不知道IntPoint):

private System.Drawing.Point[] ToPointsArray(List<IntPoint> points)
{
    System.Drawing.Point[] array = new System.Drawing.Point[points.Count];
    int i = 0;
    foreach (IntPoint p in points)
    {
        array[i++] = new System.Drawing.Point(p.X, p.Y);
    }
    return array;
}

此外,你在for循环中破坏了你的形象。此代码有效:

public void DetectCorners()
{
    // Load image and create everything you need for drawing
    Bitmap image = new Bitmap(@"C:\Users\ssammour\Desktop\Unbenannt.PNG");
    BlobCounter blobCounter = new BlobCounter();
    blobCounter.ProcessImage(image);
    Bitmap result = new Bitmap(image.Width, image.Height, Graphics.FromImage(image));
    Graphics g = Graphics.FromImage(result);
    g.DrawImage(image,0,0);
    Blob[] blobs = blobCounter.GetObjectsInformation();
    SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
    Pen redPen = new Pen(Color.Red);
    for (int i = 0, n = blobs.Length; i < n; i++)
    {
        List<IntPoint> corners;
        List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

        if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
        {
            corners.Dump();
            g.DrawPolygon(redPen, ToPointsArray(corners, image.Height));
        }
    }
    result.Save(@"c:\result.png", ImageFormat.Png);
}

我得到了以下几点:

(0 0),(574 0),(574 398),(0 398)

(161 391),(162 390),(165 393),(165 394)

(301 394),(304 392),(310 398),(303 398)

(552 398),(558 392),(561 392),(562 398)

(155 397),(156 396),(157 398),(155 398)

所以,看起来BlobCounter并没有找到你想要的blob。