cv2.findContours(img,mode,method)
mode:轮廓检索模式
method:轮廓逼近方法
首先导入图像:
# 为了更高的准确率,使用二值图像。
img = cv2.imread('contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv_show(thresh, 'thresh')
使用cv2.findContours()函数将轮廓提取出来:
# 提取轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETE_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 查看提取的轮廓数量
np.array(contours).shape
将轮廓绘制出来:
# 绘制轮廓
# 注意需要copy,要不原图会变。。。
draw_img = img.copy()
res1 = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2) # -1表示绘制所有轮廓
draw_img = img.copy()
res2 = cv2.drawContours(draw_img, contours, 0, (0, 0, 255), 2) # 0表示绘制第一条轮廓
# 展示结果
res = np.hstack((res1, res2))
cv2.imwrite('contours_drawing.png', res)
# 首先,取出需要获取特征的那条轮廓
cnt = contours[0]
# 面积
cv2.contourArea(cnt)
# 周长
cv2.arcLength(cnt, True)
# 提取轮廓并绘制轮廓
img = cv2.imread('contours2.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
draw_img = img.copy()
res1 = cv2.drawContours(draw_img, [cnt], -1, (0, 0, 255), 2)
# 近似轮廓
epsilon = 0.1*cv2.arcLength(cnt, True) # 设置阈值,阈值越小,轮廓越近似
approx = cv2.approxPolyDP(cnt, epsilon, True)
draw_img = img.copy()
res2 = cv2.drawContours(draw_img, [approx], -1, (0, 0, 255), 2)
# 展示结果
res = np.hstack((res1, res2))
cv2.imwrite('contours_drawing.png', res)
将轮廓用矩形包围起来。仍用上图举例:
# 边界矩形
img = cv2.imread('contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
x, y, w, h = cv2.boundingRect(cnt)
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv_show(img, 'img')
将轮廓用一个外接圆包围起来。仍用上图举例:
# 外接圆
img = cv2.imread('contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 255, 0), 2)
cv_show(img, 'img')