Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Python OpenCV 365 day learning plan, enter the graphics realm with eraser. This blog is the 36th in the series.

Foundation of basic knowledge

In an image, contour can be simply understood as a curve connecting all continuous points (boundaries) with the same color. Contour can be used in the fields of shape analysis, object detection and recognition.

The principle of contour discovery is: firstly, the object is extracted by threshold segmentation, and then the object contour is extracted by edge detection. An outline is a series of points (pixels) that form an ordered set of points.

The cv2.findContours function can be used to detect the edges of an image.

Function prototype description

contours, hierarchy = cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])
Copy the code

I use Python OpenCV 4.0 or higher, and if you use Python OpenCV 3.0 or higher, there may be a difference in the return value. The parameters are described as follows:

  • image: Input image;
  • mode: Contour retrieval mode, refer to the following for details;
  • method: contour approximation method, specifically described in the following text;
  • contours: Returned contour;
  • hierachy: Attributes corresponding to each contour;
  • offset: Optional offset by which each contour point moves.

Note: The image parameter needs to be a binary image, not a grayscale image, and the returned result is a contour line and hierarchy.

There are four contour retrieval modes

  • cv2.RETR_EXTERNAL: indicates that only the outer contour is detected.
  • cv2.RETR_LIST: Detection of the contour, do not establish a hierarchical relationship;
  • cv2.RETR_CCOMP: Create two levels of outline, the upper layer is the outer boundary, the inner layer is the inner hole boundary information. If there is another connected object in the inner hole, the boundary of this object is also on the top floor;
  • cv2.RETR_TREE: Creates an outline of the hierarchical tree structure.
  • The above content can be queried on the website: official website address

Contour approximation method

  • cv2.CHAIN_APPROX_NONE: Stores all contour points, and the pixel position difference between the two adjacent points is no more than 1, i.emax(abs(x1-x2),abs(y2-y1))==1, usually not used;
  • cv2.CHAIN_APPROX_SIMPLE: Compresses elements in the horizontal, vertical and diagonal directions to retain only the end coordinates of the directions. For example, a rectangular outline only needs 4 points to store the outline information.
  • cv2.CHAIN_APPROX_TC89_L1.cv2.CV_CHAIN_APPROX_TC89_KCOSUse:teh-Chinl chainApproximate algorithm (not looking for information to learn).

With that in mind, you can apply the contour discovery function as follows:

import cv2 as cv

src = cv.imread("./both.jpeg")

gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 150.255.0)
cv.imshow("thresh",thresh)
# Look for contours
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
Copy the code

After the contour is discovered, it is also required to draw the contour through the cv2.drawContours function, which is prototyped as follows:

image = cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])
Copy the code

The parameters are described as follows:

  • image: Input image;
  • contoursThe outline, in Python, is a listcv2.findContoursThe set of points found by the function, a list;
  • contourIdx: Index of contours, specifying which contours in the list to draw. To draw all contours, pass -1.
  • color: color;
  • thickness: thickness, if it is -1, it means filling;
  • lineType: linear;
  • hierarchy: Optional information about the hierarchy;
  • maxLevel: The maximum level for drawing contours, 0: draw only the specified contours, 1: Draw outline and all nested contours, 2: Draw outline, all nested contours, all nested to nested contours;
  • offset: Parameter of contour offset.

The test code and running results are as follows:

import cv2 as cv
# help(cv.drawContours)
src = cv.imread("./both.jpeg")

gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 150.255.0)
cv.imshow("thresh",thresh)
# Look for contours
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

# print(contours)
# print(hierarchy)
# Draw outline
cv.drawContours(src,contours,-1, (200.0.150),2)

cv.imshow('src',src)
cv.waitKey(0)
Copy the code