[FIXED] OpenCVSharp's findContour returns wrong data

Issue

I am trying to implement a function that finds contours in a binary image and filter out small ones.

Here's my code and a sample image. It's a super simple function that removes small area blobs. But I keep getting "contours of edges" instead of contours of regions. :S

    private IplImage RemoveNoise( IplImage image, int minArea )
    {

        List<CvPoint[]> listOfPoints = new List<CvPoint[]>();

        CvSeq<CvPoint> contoursRaw;

        List<ContourData> contours = new List<ContourData>();
        using( CvMemStorage storage = new CvMemStorage() )
        {
            //find contoures
            //Cv.FindContours( image, storage, out contoursRaw );
            Cv.FindContours( image, storage, out contoursRaw, CvContour.SizeOf, ContourRetrieval.Tree, ContourChain.ApproxSimple );
            //contoursRaw = Cv.ApproxPoly( contoursRaw, CvContour.SizeOf, storage, ApproxPolyMethod.DP, 3, true );

            while( contoursRaw != null )
            {
                CvSeq<CvPoint> result = contoursRaw;
                double area = Cv.ContourArea( result );

                //filter out small regions
                if( area >= minArea )
                {                   
                    List<CvPoint> points = new List<CvPoint>();
                    int i = 0;
                    while( result[ i ] != null )
                    {
                        points.Add( new CvPoint( result[ i ].Value.X, result[ i ].Value.Y ) );
                        i++;
                    }
                    listOfPoints.Add( points.ToArray() );

                }
                contoursRaw = contoursRaw.HNext;
            }
        }

        // draw large regions
        IplImage output = new IplImage( image.Size, image.Depth, 1 );
        output.Set( CvColor.Black );
        CvPoint[][] ArrayOfPoints = listOfPoints.ToArray();
        output.FillPoly( ArrayOfPoints, CvColor.White );

        return output;
    }

Why do I keep getting "contour of edges" instead of contour of regions?

And here is the result: enter image description here enter image description here


Solution

Try this.

IplImage input = new IplImage(@"C:\Users\20396600\Downloads\cont.jpg");
IplImage gray = new IplImage(input.Size, BitDepth.U8, 1);
IplImage invert = gray.Clone();
input.CvtColor(gray, ColorConversion.BgrToGray);
gray.Threshold(invert, 70, 255, ThresholdType.BinaryInv);
RemoveNoise(invert, 150);

private IplImage RemoveNoise(IplImage image, int minArea)
{
    IplImage output = new IplImage(image.Size, BitDepth.U8, 3);//image.Depth, 1);
    output.Set(CvColor.Black);
    CvSeq<CvPoint> contoursRaw;

    using (CvMemStorage storage = new CvMemStorage())
    {
        //find contours
        Cv.FindContours(image, storage, out contoursRaw, CvContour.SizeOf, ContourRetrieval.Tree, ContourChain.ApproxSimple);

        //Taken straight from one of the OpenCvSharp samples
        using (CvContourScanner scanner = new CvContourScanner(image, storage, CvContour.SizeOf, ContourRetrieval.Tree, ContourChain.ApproxSimple))
        {
            foreach (CvSeq<CvPoint> c in scanner)
            {
                //Some contours are negative so make them all positive for easy comparison
                double area = Math.Abs(c.ContourArea());
                //Uncomment below to see the area of each contour
                //Console.WriteLine(area.ToString());
                if (area >= minArea)
                {
                    List<CvPoint[]> points = new List<CvPoint[]>();
                    List<CvPoint> point = new List<CvPoint>();
                    foreach (CvPoint p in c.ToArray())
                        point.Add(p);

                    points.Add(point.ToArray());

                    //Use FillPoly instead of DrawContours as requested
                    output.FillPoly(points.ToArray(), CvColor.Red, LineType.AntiAlias);

                    //-1 means fill the polygon
                    //output.DrawContours(c, CvColor.White, CvColor.Green, 0, -1, LineType.AntiAlias);

                    //Uncomment two lines below to see contours being drawn gradually
                    //Cv.ShowImage("Window", output);
                    //Cv.WaitKey();
                }
            }
        } 
    }
    output.SaveImage("output.png");

    return output;
}

Based on the request for an explanation here is the secret sauce.

  1. Invert your image helps find the contours properly. FindContour wants to find white objects on black backgrounds.
  2. The ContourArea() was returning negative values so Math.Abs() helps to filter down to what you want.
  3. The DrawContour() function will fill in the contour if -1 is passed as thickness.

Everything else works very similar as the Samples provided in the OpenCvSharp downloads. Hope this helps.

Edit: Via another channel, author asked to be able to use FillPoly instead of DrawContours so the example code has been updated to reflect that.



Answered By - Darren
Answer Checked By - Robin (sql.easybugfix Admin)

Related Posts

Post a Comment