OpenCV image recognition from zero to proficient (----profile)

Source: Internet
Author: User

When looking at the contour, there is no way to find out what, because the relationship contour seems to have a lot of things, such as detection contour, extract contour, contour tracking, contour area, perimeter, marker, matching, and a series of external minimum rectangle, circle, ellipse, image moment, fill hole, etc., have to say something really good.

The contours are actually the easiest to associate with edge detection, and there are a lot of the same, but I understand that the edge is detection, is preprocessing, and the contour is probably the feature you want to use.

One, function: One is to find, one is to draw

<span style= "FONT-SIZE:18PX;" >void findcontours//extract contour, used to extract the contour of the image (Inputoutputarray image,//input image, must be a 8-bit single-channel image, and should be converted to two values of outputarrayofarrays contours,//detects the contour, each contour is represented as a point vector outputarray hierarchy,//optional output vector, which contains the topology information of the image. Where the number of elements and the amount of detected outlines are equal int mode,//description requires the contour type and the desired return value way int method,//Contour approximation method Point offset = point ()) </span>
Note: Mode Contour retrieval Modes


The cv_retr_external detects only the outer contour, or C0. The first contour in Figure 2 points to the outer sequence, except that there is no other connection.

Cv_retr_list detects all the contours and saves them to the table (list), the table is depicted in Figure 2, and the 9 outlines found are connected to each other by H_prev and H_next. There is no vertical connection, and V_prev and V_next are not used.

The Cv_retr_comp detects all the contours and organizes them into two layers of structure, the first layer is the outer contour boundary, and the second boundary is the hole boundary. From Figure 2 You can see the boundaries of 5 outlines, 3 of which contain holes. The outermost boundary C0 has two holes, and all the holes between the C0 are connected by H_prev and h_next pointers to each other.

The cv_retr_tree detects all contours and re-establishes the mesh contour structure. In Figure 2, the root node is the outermost boundary c0,c0 below the hole h00, which is connected to another hole h01 in the same layer. Similarly, each hole has child nodes (relative to c000 and c010), and the child nodes and parent nodes are vertically connected. This step persists to the contour of the image's inner layer, which becomes the leaf node.


Note that method is also an approximation of the contour

Cv_chain_code output the contour with the Freeman chain Code, and other methods output the polygon (the sequence of vertices).

Cv_chain_approx_none converts all points in the chain code encoding to points.

Cv_chain_approx_simple compresses horizontal, vertical, or oblique portions, saving only the last point.

Cv_chain_approx_tc89_l1,cv_chain_qpprox_tc89_kcos uses one of the Teh-chin chain approximation algorithms.

Cv_link_runs is completely different from the above algorithm, connecting all horizontal levels of the contour.



<span style= "FONT-SIZE:18PX;" >void drawcontours//draws outlines that are used to draw the contour of the image found (Inputoutputarray image,//the image to draw the outline inputarrayofarrays contours,//all the input outlines, Each contour is saved as a point vector int contouridx,//Specifies the number to draw the outline, and if it is negative, all contours are plotted const scalar& color,//the color used to draw the outline int thickness = 1,// The thickness of the line that draws the outline, and if it is negative, the contour is filled with int linetype = 8,/The line that draws the contour is connected Inputarray hierarchy = Noarray (),//optional parameters about the hierarchy, and int max is used only when drawing a partial outline Level = int_max,//draws the highest levels of the contour, this parameter is valid only when the hierarchy is valid                                          //maxlevel=0, the drawing and the input contour belongs to the same rank all contour namely the input contour and its adjacent outline                                          // Maxlevel=1, draws all outlines of the same level as the input contour with its child nodes.                                          //maxlevel=2, draws all outlines of the same level as the input contour with their child nodes and child nodes of the subnodes point offset = point ()) </span>
the specific usage

<span style= "FONT-SIZE:18PX;" > #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream>using namespace cv;using namespace std; #define WINDOW_NAME1 "Original map Window" "#define WINDOW_NAME2" "Contour" "Mat g_srcimage; Mat g_grayimage;int G_nthresh = 80;int G_nthresh_max = 255; RNG g_rng (12345); Mat g_cannymat_output;vector<vector<point>> g_vcontours;vector<vec4i> g_vHierarchy;void on_ Threshchange (int, void*); int main (int argc, char** argv) {g_srcimage = Imread ("lena.jpg", 1); if (!g_srcimage.data) {p rintf ("read the picture error, please determine if there is a Imread function in the directory to specify the picture exists!") \ n "); return false; } cvtcolor (G_srcimage, G_grayimage, Color_bgr2gray); Blur (G_grayimage, G_grayimage, Size (3,3)); Namedwindow (WINDOW_ NAME1, window_autosize); Imshow (window_name1, g_srcimage);//create scroll bar and initialize Createtrackbar ("Canny threshold", window_name1, &g _nthresh, G_nthresh_max, On_threshchange) on_threshchange (0, 0); Waitkey (0); return (0);} void On_threshchange (int, void*) {Canny (G_grayimage, G_cAnnymat_output, G_nthresh, g_nthresh*2, 3); Imshow ("1", g_cannymat_output);//Look for Contour findcontours (G_cannymat_output, G_ Vcontours, G_vhierarchy, Retr_tree, Chain_approx_simple, point (0, 0));//Draw contour Mat drawing = Mat::zeros (g_cannymat_output . Size (), CV_8UC3), for (int i =0; i< g_vcontours.size (); i++) {Scalar color = scalar (g_rng.uniform (0, 255), g_rng.unif ORM (0,255), G_rng.uniform (0,255));//Any value drawcontours (drawing, g_vcontours, I, color, 2, 8, G_vhierarchy, 0, point ());} Show Imshow (window_name2, drawing);} </span>


Second, the other functions

    • Returns the outer rectangle boundary Boundingrect ()
    • Finding the smallest bounding rectangle mina hot arect ()
    • Looking for the smallest enclosing circular minenclosingcircle ()
    • Ellipse fitting Two-D point set Fitellipse ()
    • Approximation of the APPROXPOLYDP curve of the polygon ()
    • Looking for convex hull convexhull ()
    • Moment moments of image
    • Contour Area Contourarea
    • Contour Curve Length Arclength
third, Matlab

Regionprops Statistics The area distribution of the marked area, showing the total number of regions. There's a lot of it that can't be more useful.

The regionprops syntax rule for the function is: STATS = Regionprops (l,properties)

This function is used to measure a series of attributes for each label area in the label Matrix L.

  • Total number of pixels in each region of the ' area ' image
  • ' BoundingBox ' contains the smallest rectangle of the corresponding area
  • ' centroid ' centroid of each region (center of gravity)
  • ' Majoraxislength ' The long axis length of the ellipse with the same standard second-order center moment as the region (in pixel sense)
  • ' Minoraxislength ' the short axis length of the ellipse with the same standard second-order center moment as the region (in pixel sense)
  • ' Eccentricity ' the eccentricity of the ellipse with the same standard second-order center moment as the region (can be used as a feature)
  • ' Orientation ' the intersection of the long axis and the x-axis of the ellipse with the same standard second-order center moment as the region (degrees)
  • ' Image ' has a logical matrix of the same size as an area
  • ' Filledimage ' has the same size fill logical matrix as an area
  • The number of on pixels in the ' filledarea ' filled area image
  • ' Convexhull ' contains the smallest convex polygon of an area
  • ' Conveximage ' draws the smallest convex polygon in the area above
  • The number of on pixels in a convex polygon image of ' convexarea ' populated area
  • A topological invariants in the ' Eulernumber ' geometric topology--Euler number
  • ' Extrema ' eight-directional region extremum Point
  • ' Equivdiameter ' diameter of the circle with the same area as the area
  • The pixel ratio of ' solidity ' at the same time in the region and its smallest convex polygon
  • The pixel scale of ' Extent ' at the same time in the region and its minimum bounding rectangle
  • Index subscript for the ' pixelidxlist ' storage area pixels
  • ' Pixellist ' stores the pixel coordinates of the above index

<span style= "FONT-SIZE:18PX;" >im=imread (' d:\lena.jpg ');                % Read Original figure,imshow (im,[]); title (' Raw ');  % Display original IM=IM2BW (IM);                       % ext. Two value image Figure,imshow (im,[]), title (' BW ');   % Display binary image Im2=imfill (IM, ' holes ');             % filled Im3=bwperim (im2);                   % Contour Extract Figure,imshow (im2,[]); Title (")             % display Figure,imshow (im3,[]);</span>


OpenCV image recognition from zero to proficient (----profile)

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.