Opencv+python Contour

Source: Internet
Author: User
Tags python list

Contours in the OpenCV

1.1 What is a contour
The contours can be simply thought of as continuous points (connected to the boundary) linked together, with the same color or grayscale. Profiles are useful for shape analysis and object detection and recognition.

    • For accuracy, use two to value the image. Threshold or canny boundary detection is required.
    • Functions that look up outlines modify the original image. If you later want to continue using the original image, you should store the original image in a different variable.
    • In OpenCV, look for contours like ultra-white objects in a black background. You should remember that the object you are looking for should be white and the background should be black.
      How to find outlines in a binary image.
      The function cv2.findcontours () has three parameters, the first one is the input image, the second is the contour retrieval mode, and the third is the contour approximation method. The return value has three, the first is the image, the second is the contour, and the third is the (contour) chromatography structure. The outline (the second return value) is a Python list that stores all the outlines in the image. Each contour is a numpy array that contains the coordinates of the object's boundary point (x, y).
      1.2 How to draw outlines
      The function cv2.drawcontours () can be used to draw outlines. It can draw any shape based on the boundary points you provide. Its first parameter is the original image, the second parameter is the outline, a Python list, and the third parameter is the index of the outline (it is useful to draw a separate contour when you set it to 1 to draw all outlines). The next parameter is the color and thickness of the contour.
      Draw all the contours on an image:
Import NumPy as Npimport Cv2img = Cv2.imread (' 1024.jpg ') Imgray = Cv2.cvtcolor (Img,cv2. Color_bgr2gray) Ret,thresh = Cv2.threshold (Imgray,127,255,0) image, Contours,hierarchy = Cv2.findcontours (thresh,cv2. Retr_tree,cv2. Chain_approx_simple) #绘制独立轮廓, such as a fourth contour#imag = Cv2.drawcontour (img,contours,-1, (0,255, 0), 3) #但是大多数时候, the following method is more useful imag = Cv2.drawcontours (img,contours,3, (0, 255,0), 3) while ( 1): Cv2.imshow ( ' Imgray ', Imgray) Cv2.imshow ( "image", image) Cv2.imshow ( ' imag ', imag) if cv2.waitkey (1) = = Ord ( ' Q '): Breakcv2.destroyallwindows ()             

1.3 Approximate method of contour
It was previously mentioned that the contour is a boundary of a shape with the same grayscale value, which stores all (x, y) coordinates on the shape boundary. In fact, we don't need all the points, when we need a straight line, we can find two endpoints. Cv2. Chain_approx_simple can be implemented. It removes redundant points on the contour, compresses the contours, and saves memory overhead.
Here's a matrix to illustrate, draw a blue circle on each coordinate in the contour list. The first shows the use of CV2. Chain_approx_none effect, a total of 734 points, the second figure is the use of CV2. The result of Chain_approx_simple is only 4 points.

2. Contour Features
2.1 Moments
The moment of the image can help us calculate the centroid, area, etc. of the image.
The function cv2.moments () returns the calculated moment as a dictionary.

import numpy as npimport cv2img = cv2.imread(‘1024.jpg‘,0)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)

Based on the values of these moments, we can calculate the center of gravity of the object:

cx=int(M[‘m10‘]/M[‘m00‘])cy=int(M[‘m01‘]/M[‘m00‘])

2.2 Contour Area
It can be calculated using the function Cv2.contourarea (), or with a moment (0 order moment), m[' m00 '.

area=cv2.contourArea(cnt)

2.3 Contour Circumference
Also known as arc length. Can be computed using the function cv2.arclength (). The second parameter of this function can be used to specify whether the shape of the object is closed (True) or open (a curve).

perimeter = cv2.arcLength(cnt,True)

2.4 Contour Approximation
Approximate contour shapes to another contour shape made up of fewer points, the number of points in the new contour is determined by the accuracy we set, using the Douglas-peucker algorithm that can own Google.
Suppose we want to look for a rectangle in an image, but for various reasons of the image we cannot get a perfect rectangle, but a "bad shape", we can use this function to approximate the shape now, the second parameter is epsilon, it is the maximum distance from the original contour to the approximate contour, It is an accuracy parameter.

epsilon=0.1*cv2.arcLength(cnt,True)approx = cv2.approxPolyDP(cnt,epsilon,True)

2.5 Convex bag
Convex hull is similar to contour, but different, although in some cases they give the same result. The function cv2.convexhull () can be used to detect whether a curve has a convex defect and can correct the defect. In general, the convex curve is always convex, at least flat. If a place is recessed, it is called a convex defect. For example, in the hand, the red curve shows the convex hull of the hand, the convex defect is marked by a double arrow.

hull = cv2.convexHull(points,hull,clockwise,returnPoints)

Parameters:

    • Points we're going to pass in the contour
    • Hull output, usually not required
    • Clockwise direction flag, if set to true, the output of the convex hull is clockwise, otherwise, counterclockwise direction.
    • Returnpoints The default value is true. It returns the coordinates of the points on the convex hull and, if set to False, returns the points on the contour corresponding to the convex hull points.
      To get the convex hull, you can use the following command:
hull=cv2.convexHull(cnt)

But if you want to get a convex defect, you need to set the returnpoints to False. Take the above rectangle for example, first we find his outline from CNT. Now set the returnpoints to true to find the convex hull and get the four corners of the rectangle. Set Returnpoints to False to get the index of the contour point.
2.6 convexity Detection
The function Cv2.iscontourconvex () can detect whether a curve is convex. It can only return true or false.

k=cv2.isContourConvex(cnt)

2.7 Bounding rectangle
Straight bounding rectangle, a straight rectangle, without rotation. does not consider whether the object is rotated. So the area of the bounding rectangle is not the smallest. The function Cv2.boundingrect () can be used to find

#(x,y)为矩形左上角的坐标,(w,h)是矩形的宽和高x,y,w,h=cv2.boundingRect(cnt)img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

Rotates the bounding rectangle, which is the smallest area of the bounding rectangle, because it takes into account the rotation of the object. Use the function Cv2.minarearect (). Returns a box2d structure that contains the width and height (w,h) and rotation angle of the rectangle's top corner coordinate (x, y) rectangle. But to draw this rectangle requires 4 corners of the rectangle, which can be obtained by the function cv2.boxpoints ().
Where Green is a straight rectangle, and red is a rotating rectangle.

2.8 min Circumscribed Circle
The function cv2.minenclosingcircle () can help us find the circumscribed circle of an object. It is the smallest of all the circles that can include objects.

(x,y),radius = cv2.minEnclosingCircle(cnt)center = (int(x),int(y))radius = int(radius)img = cv2.circle(img,center,radius,(0,255,0),2)

2.9 Ellipse Fitting
Using the function Cv2.ellipse (), the return value is actually the inscribed circle of the rotated bounding rectangle.

ellipse = cv2.fitEllipse(cnt)img = cv2.ellipse(img,ellipse,(0,255,0),2)

2.10 Straight Line Fitting
You can fit a straight line according to a set of points, and we can also fit a line to the white point in the image.

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)

Opencv+python Contour

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.