opencv learning seventeen: contour discovery

Contour discovery

After the target object in the image is extracted by threshold segmentation, it is necessary to extract the contour of the target object through edge detection. The two methods can basically determine the edge or foreground of the object. Next, what usually needs to be done is to fit the foreground of these edges, such as fitting the smallest outer rectangle, circle, convex hull and other geometric shapes containing the foreground or edge pixels, so as to lay a solid foundation for operations such as calculating their area or template matching. Foundation.

An outline represents a series of points (pixels), this series of points constitute an ordered set of points, so an outline can be understood as an ordered set of points.

Contour discovery is based on the basis of image edge extraction, a method to find the contour of the object, so the selection of the threshold for edge extraction will affect the final contour discovery
Insert picture description here

Contour discovery API

cv2.findContours()
cv2.drawContours()
finds where the contour is through cv2.findContours(), and then draws the found contour through cv2.drawContours().

contours,hierarchy=cv2.findContours(image,mode,method)
contours: contour
hierarchy: image topological information (contour level) (store the previous contour, parent contour...)
image: binary image
mode: contour retrieval method
method: contour Approximation

Insert picture description hereInsert picture description here

r=cv2.drawContours(image, contours, contourIdx, color[, thickness])
r: target image
image: original image
contours: all input contour edge array
contourIdx: edge index to be drawn, if all drawn as -1. If there are multiple targets, you can draw the first target 0, the second target 1, and the third target 2.
color: the color to be drawn, which is SCalar in BGR format.
Thickness: optional, the density of the drawing, that is, the thickness of the outline brush

import cv2 as cv
import numpy as np


def contours_demo(image):
    dst = cv.GaussianBlur(image, (3, 3), 0)
    gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)#cv.THRESH_OTSU自动寻找阈值
    cv.imshow("binary image", binary)

    cloneImage, contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    for i, contour in enumerate(contours):
        cv.drawContours(image, contours, i, (0, 0, 255), 2)
        print(i)
    cv.imshow("detect contours", image)

src = cv.imread("C:/Users/lenovo/Desktop/opencv/daima/banknum/template-matching-ocr/images/circle.png")  #读取图片位置
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
contours_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()

Run screenshot:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44145452/article/details/112789303