今天学习轮廓检测方法
import cv2
import numpy as np
def cv_show_image(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('images/contour.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv_show_image('binary_src_img', threshold)
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
print(len(contours))
print(type(contours))
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, contourIdx=-1, color=(0, 255, 0), thickness=1)
cv_show_image('draw_contours_img', res)
for i in range(len(contours)):
cont = contours[i]
print('第{}轮廓的面积是{},周长是{}', i, cv2.contourArea(cont), cv2.arcLength(cont, True))
draw_img = img.copy()
for i in range(len(contours)):
cont = contours[i]
epsilon = 0.03 * cv2.arcLength(cont, True)
approx = cv2.approxPolyDP(cont, epsilon, True)
draw_img = cv2.drawContours(draw_img, [approx], contourIdx=-1, color=(0, 255, 0), thickness=1)
cv_show_image('approx_contours_img', draw_img)
draw_img = img.copy()
for i in range(len(contours)):
cont = contours[i]
x,y,w,h = cv2.boundingRect(cont)
draw_img = cv2.rectangle(draw_img, pt1=(x,y), pt2=(x+w, y+h), color=(0, 255, 0), thickness=2)
cv_show_image('rectangle_contours_img', draw_img)
draw_img = img.copy()
for i in range(len(contours)):
cont = contours[i]
(x,y), radius = cv2.minEnclosingCircle(cont)
center = (int(x), int(y))
radius = int(radius)
draw_img = cv2.circle(draw_img, center=center, radius=radius, color=(0, 255, 0), thickness=2)
cv_show_image('circle_contours_img', draw_img)
原始图像如下: 画出所有轮廓: 轮廓有内部轮廓和外部轮廓,如果使用mode = RETR_EXTERNAL 可只画出外轮廓
画出所有近似轮廓: 画出所有轮廓的外接最大矩形
画出所有轮廓的外接最大圆形
|