Link to the original text :http://www.juzicode.com/opencv-python-findcontours-drawcontours
return Opencv-Python course
Image contour is used to describe continuous points in an image , They have the same color and gray scale . For more accurate detection , Before finding the contour, the image needs to be binarized or used canny Edge detection . stay OpenCV In contour detection, only white objects are found , Black background is ignored .
contours,hierarchy=cv2.findContours(image,mode,method[,contours[,hierarchy[,offset]]])
mode The name and meaning of :
mode meaning cv2.RETR_EXTERNAL Only the external contour is extracted , Set up hierarchy[i][2]=hierarchy[i][3]=-1 cv2.RETR_LIST Extract all the contours , It does not include the hierarchical relationship between contours cv2.RETR_CCOMP Extract all the contours , contain 2 Hierarchical relationship , The top layer is the outer boundary , The bottom layer is the interior hole. If there are multiple nesting , Still, in accordance with the 2 Layer organization . cv2.RETR_TREE Organize according to the complete hierarchical relationship cv2.RETR_FLOODFILLmethod The name and meaning of :
method meaning cv2.CHAIN_APPROX_NONE Store all inter edge points , Whether it's vertical 、 Horizontally or diagonally cv2.CHAIN_APPROX_SIMPLE vertical direction 、 Only the end point is reserved in the horizontal or diagonal direction , For example, a rectangle contains only 4 vertices cv2.CHAIN_APPROX_TC89_L1 Use teh-Chini The approximate algorithm cv2.CHAIN_APPROX_TC89_KCOS Use teh-Chini The approximate algorithmThe following is an example of finding an outline , Read image , After graying, binarization is performed , And then call findContours() Find the outline :
import numpy as np
import cv2
print('VX official account : orange code / juzicode.com')
# Read image 、 Grayscale 、 Two valued
img_src = cv2.imread('..\\samples\\picture\\contours1.bmp')
img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
val, img_bin = cv2.threshold(img_gray,127,255, cv2.THRESH_BINARY)
#cv2.imwrite('contours-bin.bmp',img_bin)
# Find the outline
contours, hierarchy=cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
print('contours:',contours)
print('type(contours):',type(contours))
print('len(contours):',len(contours))
print('type(contours[0]):',type(contours[0]))
print('contours[0].shape:',contours[0].shape)
print('hierarchy:',hierarchy)
print('type(hierarchy):',type(hierarchy))
print('len(hierarchy):',len(hierarchy))
print('hierarchy.shape:',hierarchy.shape)
Running results :
VX official account : orange code / juzicode.com
contours: [array([[[159, 150]],
[[159, 241]],
[[307, 241]],
[[307, 150]]], dtype=int32), array([[[330, 28]],
[[330, 100]],
[[434, 100]],
[[434, 28]]], dtype=int32), array([[[ 23, 20]],
[[ 23, 114]],
[[172, 114]],
[[172, 20]]], dtype=int32)]
type(contours): <class 'list'>
len(contours): 3
type(contours[0]): <class 'numpy.ndarray'>
contours[0].shape: (4, 1, 2)
hierarchy: [[[ 1 -1 -1 -1]
[ 2 0 -1 -1]
[-1 1 -1 -1]]]
type(hierarchy): <class 'numpy.ndarray'>
len(hierarchy): 1
hierarchy.shape: (1, 3, 4)
contours Is a list of profiles found , By n Composed of three outlines list, Each contour is a numpy Array , its shape by (m,1,2),m The number of pixels formed for the contour , Every point has 2 A numerical , Respectively x and y coordinate .
hierarchy Of shape by (1,n,4),n Corresponding contours The number of n, So visit page i An outline hierarchy Time use hierarchy[0][i] Express . Every hierarchy The elements of 4 It's made up of values , In turn next,previous,first child and parent, Represents the next node , Last node , First child node , Parent node .
drawContours(image,contours,contourIdx,color[,thickness[,lineType[,hierarchy[,maxLevel[,offset]]]]])->image
The following example finds the contour and draws the contour in turn :
import numpy as np
import cv2
print('VX official account : orange code / juzicode.com')
# Read image 、 Grayscale 、 Two valued
img_src = cv2.imread('..\\samples\\picture\\contours1.bmp')
cv2.imshow('img_src',img_src)
img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
val, img_bin = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
# Find the outline
contours, hierarchy=cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
print('len(contours):',len(contours))
# Draw the outline
for ind in range(len(contours)):
cv2.drawContours(img_src, contours, ind, (0,0,255), 3)
cv2.imshow('con',img_src)
cv2.waitKey()
Running results :
Can also be contourIdx Set to -1, Draw all contours at once :
# Set to -1, Draw all contours
cv2.drawContours(img_src, contours, -1, (0,0,255), 3)
cv2.imshow('con',img_src)
cv2.waitKey()
Set up offset Parameters :
cv2.drawContours(img_src, contours, -1, (0,0,255), 3, offset=(10,10))
The drawn border is offset as a whole offset Pixel :
問題遇到的現象和發生背景使用python中optimize.
Catalog introduction One 、 R