opencv-python(九):轮廓查找

1、轮廓查找

轮廓查找就是将二值化后的边缘,利用近邻之间连续性,按照顺序依次进行连接,获知物体的轮廓信息。

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('T.png', 1)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

# draw contours
cv.drawContours(img, contours, -1, (0, 255, 0), 3)

plt.subplot(111), plt.imshow(img, cmap = 'gray')
plt.title('contours'), plt.xticks([]), plt.yticks([])

plt.show()

效果如下:


注:findContours函数的参数:第一个对应于二值图像,第二个对应于搜索模式,第三个对应于轮廓的近似方法。

2、轮廓的矩、面积和弧长

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('T.png', 1)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
im1, contours, hierarchy = cv.findContours(thresh,  cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

cnt = contours[0]
cv.drawContours(img, contours, 0, (255, 0, 0), 3)
M = cv.moments(cnt)

# centroid
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
# show
cv.circle(img, (cx, cy), 20, (0, 255, 0), 3)

# contour Area
print(cv.contourArea(cnt))

# arc length
print(cv.arcLength(cnt, True))

plt.subplot(111), plt.imshow(img)
plt.title('centroid'), plt.xticks([]), plt.yticks([])

plt.show()

效果如下:




猜你喜欢

转载自blog.csdn.net/sinat_31425585/article/details/80247959