opencv foundation 48 - draw image contour and cut example - cv2.drawContours()

Drawing image contours: drawContours function

In OpenCV, image contours can be drawn using the function cv2.drawContours(). The syntax of this function is:

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

Among them, the return value of the function is image, which represents the target image, that is, the original image with the edge drawn.
This function has the following parameters:

  1. image: The image to draw the outline. It should be noted that the function cv2.drawContours() will draw the contour directly on the image image. That is to say, after the function is executed, the image is no longer the original image, but the image containing the outline. Therefore, if the image image has other uses, you need to make a copy in advance, and pass the copy image to the function cv2.drawContours() for use.

  2. contours: the contours to be drawn. The type of this parameter is the same as the output contours of the function cv2.findContours(), both of which are list types.

  3. contourIdx: The index of the edge to be drawn, telling the function cv2.drawContours() whether to draw a certain contour or all contours. If the parameter is an integer or zero, it means to draw the contour of the corresponding index number; if the value
    is negative (usually "-1"), it means to draw all the contours.

  4. color: the color to draw, expressed in BGR format.

  5. thickness: an optional parameter, indicating the thickness of the brush used when drawing the outline. If the value is set to "-1", it means
    to draw a solid outline.

  6. lineType: optional parameter, indicating the line type used when drawing the outline.

  7. hierarchy: corresponds to the hierarchical information output by the function cv2.findContours().

  8. maxLevel: Controls the depth of the drawn outline hierarchy. If the value is 0, it means that only the outline of the 0th layer is drawn; if the value is other non-zero positive numbers, it means that the outline of the highest level and the same number of levels below are drawn.

  9. offset: Offset parameter. This parameter offsets the outline to a different position for display.

The parameter image and the return value image of the function cv2.drawContours() have the same value after the function operation. Therefore, the function cv2.drawContours() can also be written in the form of no return value:

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

Code example: Draw all contours in an image.

If you want to draw all the contours in the image, you need to set the value of the parameter contourIdx of the function cv2.drawContours() to "-1". The downloadable code in the previous section of
the original experimental picture is as follows:

import cv2
o = cv2.imread('contours.bmp')
cv2.imshow("original",o)
#将原图像转换为灰度图像
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
#将灰度图像转换为二值图像
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
#寻找轮廓,返回的contours是轮廓的列表,hierarchy是每个轮廓对应的属性
contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
#绘制轮廓,contours是轮廓的列表,-1表示绘制所有轮廓,(0,0,255)表示轮廓颜色为红色,5表示轮廓宽度为5
o=cv2.drawContours(o,contours,-1,(0,0,255),5)
cv2.imshow("result",o)
cv2.waitKey()
cv2.destroyAllWindows()

The running effect is as follows:

insert image description here
In this program, the color of the outline is set to red (due to black and white printing, it is displayed as gray in the paper book), that is,
(0, 0, 255), and the parameter thickness (thickness of the outline line) is set to " 5".

Example 2 Cut edge information in an image one by one.

import cv2
import numpy as np
o = cv2.imread('contours.bmp')
#显示原始图像
cv2.imshow("original",o)
#将原图像转换为灰度图像
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
#将灰度图像转换为二值图像
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
#寻找轮廓,返回的contours是轮廓的列表,hierarchy是每个轮廓对应的属性
contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
#获取轮廓的数量
n=len(contours)
#对每个轮廓进行绘制
contoursImg=[]
for i in range(n):
    #创建空白画布
 temp=np.zeros(o.shape,np.uint8)
 contoursImg.append(temp)
 #绘制轮廓,contours是轮廓的列表,i表示绘制第i个轮廓,(255,255,255)表示轮廓颜色为白色,5表示轮廓宽度为5
 contoursImg[i]=cv2.drawContours(contoursImg[i],contours,i,(255,255,255),5)
 cv2.imshow("contours[" + str(i)+"]",contoursImg[i])
cv2.waitKey()
cv2.destroyAllWindows()

insert image description here
insert image description here

Example 3: Using the contour drawing function to extract foreground objects.

Set the value of the parameter thickness of the function cv2.drawContours() to "-1" to draw the solid outline of the foreground object. The foreground object can be extracted from the original image by performing a "bitwise AND" operation on the solid outline and the original image.

code show as below:

import cv2
import numpy as np
o = cv2.imread('loc3.jpg')
cv2.imshow("original",o)
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
#创建空白画布
mask=np.zeros(o.shape,np.uint8)
#绘制轮廓,contours是轮廓的列表,-1表示绘制所有轮廓,(255,255,255)表示轮廓颜色为白色,-1表示轮廓宽度为-1,表示对轮廓进行填充
mask=cv2.drawContours(mask,contours,-1,(255,255,255),-1)
#显示掩膜
cv2.imshow("mask" ,mask)
#将原图像和掩膜进行位运算
loc=cv2.bitwise_and(o,mask)
cv2.imshow("location" ,loc)
cv2.waitKey()
cv2.destroyAllWindows()

In this example, the parameter thickness of the function cv2.drawContours() is set to "-1", and the solid outline mask of the foreground object is obtained
. Next, use the statement "cv2.bitwise_and(o, mask)" to perform a "bitwise AND" operation on the original image o and the solid contour mask
to obtain the foreground object of the original image.

operation result:

  • The left image is the original image with a small flower as the foreground object.
  • The middle image is the solid outline of the floret obtained from the original image.
  • The image on the right is the extracted foreground object floret.
    insert image description here
    insert image description here

The original picture of the experiment
insert image description here

Guess you like

Origin blog.csdn.net/hai411741962/article/details/132169044