程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Opencv Python tutorial: find contour, draw contour

編輯:Python

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 .

1、 Find the outline findContours()

contours,hierarchy=cv2.findContours(image,mode,method[,contours[,hierarchy[,offset]]])
  • Parameter meaning :
  • image: The input image ,8bit single channel ; The value of the image element is 0 Background representation , Not 0 Value indicates foreground , To find the contour accurately , It is best to binarize the original image . If mode Parameter is RETR_CCOMP or RETR_FLOODFILL The input image can also be 32bit Single channel image (CV_32SC1). however floodfill I won't support it cv-8u type
  • mode: Contour extraction mode .
  • method: Contour approximation .
  • contours: Contour found .
  • hierarchy: Find the outline hierarchy .
  • offset: Offset value , Use ROI It is used to calculate the original position .

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_FLOODFILL

method 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 algorithm

The 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 .

2、 Draw the outline drawContours

drawContours(image,contours,contourIdx,color[,thickness[,lineType[,hierarchy[,maxLevel[,offset]]]]])->image
  • Parameter meaning :
  • image: The image to draw the border , The image will be modified after calling .
  • contours: Outline list , General introduction findContours() Found border .
  • contourIdx:contours The index of , That is, the number of borders to represent , If you want to draw all the borders , Set to a negative number .
  • color: Color ,bgr Three parameters tuple.
  • thickness: The width of the border .
  • lineType: Boundary line type .
  • hierarchy: rely on maxLevel Use , If maxLevel Set to 1 and 2 This parameter is used when ,
  • maxLevel:
  • offset: Border offset position

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 :

Extended reading :

  1. OpenCV-Python course

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved