OPENCV (Python) Tutorial-Contour (2) Contour feature __python

Source: Internet
Author: User
Tags scale image
Goal

Look for different features of the contour, such as area, perimeter, center of gravity, bounding box, etc., which will be used in many future image recognition.

The key problem of the concept image recognition of moment is the feature extraction of image, the simple description is to use a set of simple data (image description) to describe the whole image, the simpler the data the more representative the better. Good features are not interfered by light, noise and geometrical deformation. Image recognition has been developed for several decades, and the invariant moment of image is one of the new features.

Moment is a concept in probability and statistics, and it is a numerical characteristic of random variable. Set X to random variable, c to constant, K to positive integer. The amount e[(X−c) K] is called the K-order moment of X about C point

There are two things that are more important:

1. c=0. At this point ak=e (Xk) is called the K-order Origin moment of X

2. C=e (X). Then μk=e[(X−ex) K] is called the K-Order center moment of X.

The first Order of Origin moment is the expectation. First-order Central moment μ1=0, the second-order central moment μ2 is the variance var (x) of X. In statistics, more than 4-order moments are rarely used. Μ3 can be used to measure whether the distribution is biased. μ4 can measure how steep the distribution (density) is in the vicinity of the mean value.

For an image, we think of pixel coordinates as a two-dimensional random variable (x,y), then a gray-scale image can be represented by two-dimensional gray-density function, so it can be used to describe the features of gray-scale images.

Invariant moment (invariant Moments) is a highly condensed image feature with translational, grayscale, scale, and rotational invariance. M.k.hu first proposed the concept of invariant moment in 1961. In the 1979 M.r.teague The Zernike moment was proposed according to the orthogonal polynomial theory.

For the specific calculation method and concept of moment, reference link http://blog.csdn.net/qq_18343569/article/details/46913501

Import cv2
import numpy as np
img = cv2.imread (' star.jpg ', 0)
Img=cv2.cvtcolor (Img,cv2. Color_bgr2gray) #彩色转灰度
Ret,thresh = Cv2.threshold (img,127,255,0)   #二值化
image,contours,hierarchy = Cv2.findcontours (Thresh, 1, 2)
cnt = contours[0]   #选取其中的第一个轮廓
M = cv2.moments (CNT)  #对第一个轮廓
Print (M)             #打印出所有计算的M的参数, the calculation formulas for each numerical reference http://blog.csdn.net/qq_18343569/article/details/46913501
cx = int (m[' M10 ']/m[') M00 '])  #X方向的重心 where m[' M10 ' represents the first-order space moment in the x direction, m[' m00 '] represents the area, and m[' m00 ' can also be computed by Cv2.contourarea () to get
cy = Int (m[' M01 ']/m[' m00 ']) #Y方向的重心

In addition, the functions on outlines include the following Contour Perimeter

Cv2.arclength ()

Perimeter = Cv2.arclength (cnt,true)
The second argument of this function can be used to specify whether the shape of the object is closed (True) or open (a curve). If it is a closed curve, that method results in the same result, if the curve is open, then the results are different, the closed method will be at the end of the starting point and the end of the length of the combination of added. Contour Approximation

Approximate the shape of the contour to another form of contour with fewer points, and the number of points in the new contour is determined by the accuracy we set. Using the Douglas-peucker algorithm, you can go to Wikipedia to get more details on this algorithm. To help understand, suppose we're looking for a rectangle in an image, but for all the reasons of the image, we can't get a perfect rectangle, but a "bad shape" (as shown in the following image). Now you can use this function to approximate this shape. The second parameter of this function is called epsilon, which is the maximum distance from the original contour to the approximate profile. It is an accuracy parameter. Choosing a good epsilon is very important for satisfying results.

Epsilon = 0.1*cv2.arclength (cnt,true)
approx = CV2.APPROXPOLYDP (cnt,epsilon,true)
Below, the Green Line in the second picture is the approximate contour obtained when epsilon = 10%, and the third is the approximate contour obtained when epsilon = 1%. The third parameter sets whether the arc is closed.


Convex bag

Convex packages are similar to contours, but different, although in some cases they give the same result. function Cv2.convexhull () can be used to detect whether a curve has convexity defects and to correct defects. In general, convex curves are always convex, at least flat. If a place is recessed, it is called a convexity defect. For example, the hand in the figure below. The red curve shows the convex package of the hand, and the convex defect is marked with a double arrow.

The reference code is:

Hull = Cv2.convexhull (points, Hull, clockwise, returnpoints)
Points we want to pass in the contour hull output, usually do not need to clockwise direction flags. If set to True, the output of the convex package is clockwise. Otherwise, counterclockwise direction. returnpoints The default value is True. It returns the coordinates of the point on the convex package. If set to False, points on the contour corresponding to the convex package point are returned.
convexity Detection

The function Cv2.iscontourconvex () can be used to detect whether a curve is convex or not. It can only return True or False.

K = Cv2.iscontourconvex (CNT)
Bounding Rectangle

a straight rectangle with a straight rectangle (that is, a rectangle without a rotation). It does not consider whether the object is rotated. So the area of the bounding rectangle is not the smallest. You can use function Cv2.boundingrect () to find it. (x,y) is the coordinate of the upper-left corner of the rectangle (w,h) is the width and height of the rectangle.

X,y,w,h = Cv2.boundingrect (CNT)
img = Cv2.rectangle (IMG, (x,y), (X+w,y+h), (0,255,0), 2)
Rotated Bounding rectangleThis bounding rectangle is the smallest area because it takes into account the rotation of the object. The function used is cv2.minarearect (). Returns a box2d structure that contains the coordinates of the upper-left corner of the rectangle (x,y), the width and height (w,h) of the rectangle, and the angle of rotation. However, to draw this rectangle requires 4 corner points of the rectangle, which can be obtained by the function cv2.boxpoints ().
Rect = Cv2.minarearect (cnt)
box = cv2.cv.BoxPoints (rect)
box = np.int0 (Box)
cv2.drawcontours (IMG, [box], 0 , (0, 0, 255), 2)
The two border rectangles are shown in the following illustration, where the green is a straight rectangle and the red is the rotated rectangle. The complete code is as follows:

# with green (0, 255, 0) to draw the smallest rectangular frame
x, y, W, h = cv2.boundingrect (CNT)
Cv2.rectangle (IMG, (x, y), (x+w, Y+h), (0, 255, 0), 2)

# A rectangular frame with a rotating angle in red
rect = Cv2.minarearect (cnt)
box = cv2.cv.BoxPoints (rect)
box = np.int0 (box)
Cv2.drawcontours (IMG, [box], 0, (0, 0, 255), 2)
cv2.imwrite (' contours.png ', IMG)


Minimum circumcircle

function cv2.minenclosingcircle () can help us find an object's tangent circle. It is the smallest of all the circles that can include an object.

(x,y), radius = cv2.minenclosingcircle (CNT)
Center = (int (x), int (y))
radius = int (RADIUS)
img = cv2.circle ( Img,center,radius, (0,255,0), 2)


Ellipse Fitting

The function used is cv2.ellipse (), and the return value is actually the incircle of the rotated bounding rectangle

Ellipse = Cv2.fitellipse (CNT)
im = Cv2.ellipse (Im,ellipse, (0,255,0), 2)
Straight Fitting

We can fit a line according to a set of points, and we can also fit a straight line for the white dots in the image.

Rows,cols = Img.shape[:2]
[vx,vy,x,y] = Cv2.fitline (CNT, CV2. dist_l2,0,0.01,0.01)
lefty = Int ((-X*VY/VX) + y)
righty = Int ((cols-x) *vy/vx) +y)
img = Cv2.line (IMG, Cols-1,righty), (0,lefty), (0,255,0), 2)










Related Article

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.