Opencv之提取图像轮廓

提取图像轮廓

cv2.findContours(img,mode,method)
mode:轮廓检索模式

  • RETR_EXTERNAL :只检索最外面的轮廓;
  • RETR_LIST:检索所有的轮廓,并将其保存到一条链表当中;
  • RETR_CCOMP:检索所有的轮廓,并将他们组织为两层:顶层是各部分的外部边界,第二层是空洞的边界;
  • RETR_TREE(最常用):检索所有的轮廓,并重构嵌套轮廓的整个层次;

method:轮廓逼近方法

  • CHAIN_APPROX_NONE:以Freeman链码的方式输出轮廓,所有其他方法输出多边形(顶点的序列)。
  • CHAIN_APPROX_SIMPLE(最常用):压缩水平的、垂直的和斜的部分,也就是,函数只保留他们的终点部分。
    以下图举例:
    在这里插入图片描述

寻找并绘制轮廓

首先导入图像:

# 为了更高的准确率,使用二值图像。
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')

得到结果为:
在这里插入图片描述

发布了36 篇原创文章 · 获赞 1 · 访问量 543

猜你喜欢

转载自blog.csdn.net/qq_36758914/article/details/104007478