Image contour extraction in OpenCV and EMGUCV

Source: Internet
Author: User


a contour is a collection of a series of points in an image that represent boundaries. Although the edge detection algorithm can check the pixel of the contour boundary based on the difference between pixels, it does not represent the contour as a whole. So the next step is to assemble the pixels that are detected at the edges into a silhouette.
OpenCV can be used to extract outlines from a two-value image using the Findcontours () function. The OpenCV generally uses sequences to store contour information. Each element in the sequence is the position of a point in the curve.
The function findcontours () looks for the contour from a two-value image. The image processed by findcontours () can be an image with an edge pixel after canny () or an image obtained after threshold (), at which point the edge is the boundary between positive and negative regions.
Before we introduce the function prototypes, we also need to understand the concept of the contour tree simply. OPENCV allows the resulting contour to be aggregated into a contour tree, which encodes the included relationship into the contour tree. Outlines that are directly contained in the contour become their child nodes. And so on


The function prototypes in OpenCV3.0 are as follows:





void Findcontours (Inputoutarray image, Outputarrayofarrays contours,  outputarray hierarchy, int mode, int method, Point offset = point ())
    • The first parameter, the Inputoutarray type of image, is the 8-bit single-channel mat type. The image's non-0 pixels are considered to be 1,0 pixels reserved as 0. This function modifies the contents of the image while extracting the outline of the line.
    • The second argument, the Outputarrayofarrays type of contours. The result of the operation after the function call is saved here, that is, the detected contour, each of which is stored as a point vector, which is represented by a vector of type points.
    • The third parameter, the Outputarray type of hierarchy, is an optional output vector that contains the topology information for the image. As a representation of the number of outlines, it contains many elements. Each contour Contours[i] corresponds to 4 hierarchy elements hierarchy[i][0]~hierarchy[i][3], respectively, representing the index number of the latter outline, the previous outline, the parent outline, and the inline contour. If there is no corresponding entry, the Hierarchy[i] value is set to a negative number.
    • The fourth parameter, the int type mode, outlines the retrieval mode.
Retr_external-Extracts only the outermost contour . For all contour settings hierarchy[i][2] = hierarchy[i][3] =-1.
retr_list-Extracts all outlines and places them in the list
Retr_ccomp-Extracts all contours and organizes them into a layer two hierarchy: The top layer is the perimeter boundary of the connected domain, and the secondary layer is the inner boundary of the hole.
Retr_tree-Extracts all contours and reconstructs all hierarchy of nested outlines
    • The fifth parameter, the method of type int, is the approach of contour approximation.            
Chain_approx_none-converts all points from chain code form to point sequence form
chain_approx_simple-Compress horizontal, vertical, and diagonal splits, i.e. the function retains only the pixel points of the end;  
chain_approx_tc89_l1, Chain_approx_tc89_kcos-Application of Teh-chin chain approximation algorithm.
    • The sixth parameter, offset of the point type, has an optional offset for each contour points, and a default value of (). This parameter can be useful when the contour is extracted from the ROI of the image, since the contour can be analyzed from the entire image context.

eg
Mat srcImage = imread ("M: / image processing experiment / contour extraction / test-1.bmp", 1);
cvtColor (srcImage, srcImage, COLOR_BGR2GRAY);
adaptiveThreshold (srcImage, srcImage, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 35, 10);
Mat result = Mat :: zeros (srcImage.size (), CV_8UC3);
srcImage.copyTo (result);
Canny (srcImage, srcImage, 3,6,3);
vector <vector <Point>> contours;
vector <Vec4i> hierarchy;
findContours (srcImage, contours, hierarchy, CV_RETR_TREE, CHAIN_APPROX_SIMPLE);
int areaMin = srcImage.cols * srcImage.rows;
for (int i = 0; i <contours.size (); i ++) {
    double area = contourArea (((contours) ._ Myfirst) [i]);
    if (area> srcImage.rows * srcImage.cols / 3) {
        // Select the smallest area that meets the conditions. Think of changing the outline to the border of the answer card.
        if (areaMin> area) {
            areaMin = area;
        } else {
            continue;
        }
        double area = contourArea (((contours) ._ Myfirst) [i]);
        Scalar color (rand () & 255, rand () & 255, rand () & 255);
        drawContours (result, contours, i, color, CV_FILLED, 8, hierarchy, 0, Point ());
    }
}
imwrite ("M: / Image processing experiment / Contour extraction / test-1-result.bmp", result);







The following is the result of the original and contour extraction:





The function prototypes in EmguCV3.0 are as follows:





Public Shared Sub FindContours(image As Emgu.CV.IInputOutputArray, contours As Emgu.CV.IOutputArray, hierarchy As Emgu.CV.IOutputArray, mode As Emgu.CV.CvEnum.RetrType, method As Emgu.CV.CvEnum.ChainApproxMethod, Optional offset As System.Drawing.Point = Nothing)
    • The first parameter, the Emgu.CV.IInputOutputArray type, is the source image. The image's non-0 pixels are considered to be 1,0 pixels reserved as 0. This function modifies the contents of the image while extracting the outline of the line.
    • The second argument, the Emgu.CV.IOutputArray type of contours. The result of the operation after the function call is saved here, that is, the detected contour, each of which is stored as a point vector, which is represented by a vector of type points.
    • The third parameter, the Emgu.CV.IOutputArray type of hierarchy, is an optional output vector that contains the topology information for the image.
    • The fourth parameter, Emgu.CV.CvEnum.RetrType type mode, outlines the retrieval mode.
Emgu.CV.CvEnum.RetrType.External-Extract only the outermost contour.
Emgu.CV.CvEnum.RetrType.List-Extracts all outlines and places them in the list 
Emgu.CV.CvEnum.RetrType.Ccomp-Extracts all contours and organizes them into two layers of hierarchy: The top layer is the perimeter boundary of the connected domain, and the secondary layer is the inner boundary of the hole.  
emgu.cv.cvenum.retrtype.tree-extracts all contours and reconstructs all hierarchy of nested outlines
    • The fifth parameter, the method of the Emgu.CV.CvEnum.ChainApproxMethod type, approaches the contour approximation.            
Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxNone-Translate (convert) all points from chain code form to point sequence form 
Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple-Compress horizontal, vertical, and diagonal splits, i.e. the function retains only the pixel points at the end; 
Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxTC89L1, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxTC89KCOS-Application Teh-chin chain approximation algorithm.
    • The sixth parameter, offset of the point type, has a default value for the optional offset of each footprint. This parameter can be useful when the contour is extracted from the ROI of the image, since the contour can be analyzed from the entire image context.

eg
Dim bkGrayWhite As New Gray (255)
Dim img As Image (Of Gray, Byte) = New Image (Of Gray, Byte) ("M: \ Image Processing Experiment \ Contour Extraction \ test-2.bmp")
Dim img_threshold As Image (Of Gray, Byte) = New Image (Of Gray, Byte) (img.Width, img.Height, bkGrayWhite)
Dim imgresult As Image (Of Rgb, Byte) = New Image (Of Rgb, Byte) (img.Width, img.Height, New Rgb (255, 255, 255))
img.CopyTo (img_threshold)
CvInvoke.AdaptiveThreshold (img_threshold, img, 255, CvEnum.AdaptiveThresholdType.MeanC, CvEnum.ThresholdType.Binary, 35, 10)
Dim imgCanny As Image (Of Gray, Byte) = New Image (Of Gray, Byte) (img.Width, img.Height, bkGrayWhite)
CvInvoke.Canny (img, imgCanny, 25, 25 * 2, 3)
Dim contours As Emgu.CV.Util.VectorOfVectorOfPoint = New Emgu.CV.Util.VectorOfVectorOfPoint ()
Dim hierarchy As Emgu.CV.IOutputArray = New Image (Of Gray, Byte) (img.Width, img.Height, bkGrayWhite)
CvInvoke.FindContours (imgCanny,
                                     contours,
                                     hierarchy,
                                     Emgu.CV.CvEnum.RetrType.External,
                                     Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple
                                      )
Dim areaMax As Integer = img.Width * img.Height
    For i = 0 To contours.Size-1
            Dim area As Integer = CvInvoke.ContourArea (contours (i))
            ‘Screen for contours with an area larger than one third of the overall picture area
            If area <areaMax / 3 Then
                Continue For
            End If
            CvInvoke.DrawContours (imgresult, contours, i, New MCvScalar (0, 0, 0), 2, CvEnum.LineType.EightConnected, hierarchy, 2147483647)
    Next
imgresult.Save ("M: \ Image Processing Experiment \ Contour Extraction \ test-2-result.bmp") 









Image contour extraction in OpenCV and EMGUCV


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.