opencv寻找图像外轮廓

本文展示如何使用opencv中的方法寻找点集的外轮廓
参考:

  1. https://docs.opencv.org/4.0.0/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0
  2. https://blog.youkuaiyun.com/eric_e/article/details/79591025

1、opencv接口函数:

contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

参数说明:

  1. image:8位单通道2值图像,如果mode参数是 RETR_CCOMP 或者 RETR_FLOODFILL,输入也可以是32-bit integer image of labels (CV_32SC1)。
  2. mode:
    (1) cv.RETR_EXTERNAL只检测最外围轮廓,包含在外围轮廓内的内围轮廓被忽略
    (2) cv.RETR_LIST   检测所有的轮廓,包括内围、外围轮廓,但是检测到的轮廓不建立等级关系,彼此之间独立,没有等级关系,这就意味着这个检索模式下不存在父轮廓或内嵌轮廓,所以hierarchy向量内所有元素的第3、第4个分量都会被置为-1。
    (3) cv.RETR_CCOMP  检测所有的轮廓,但所有轮廓只建立两个等级关系,外围为顶层,若外围内的内围轮廓还包含了其他的轮廓信息,则内围内的所有轮廓均归属于顶层。
    (4) cv.RETR_TREE, 检测所有轮廓,所有轮廓建立一个等级树结构。外层轮廓包含内层轮廓,内层轮廓还可以继续包含内嵌轮廓。
    (5) cv.RETR_FLOODFILL,官方文档中没有说明
  3. method:
    (1) cv.CHAIN_APPROX_NONE 保存物体边界上所有连续的轮廓点到contours向量内
    (2) cv.CHAIN_APPROX_SIMPLE 仅保存轮廓的拐点信息,把所有轮廓拐点处的点保存入contours向量内
    (3) cv.CHAIN_APPROX_TC89_L1 使用Teh-Chin chain approximation algorithm
    (4) cv.CHAIN_APPROX_TC89_KCOS 使用Teh-Chin chain approximation algorithm
  4. contours:轮廓点数(python中该参数保持默认值None即可)
  5. hierarchy:Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i], the elements hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.(python中该参数保持默认值None即可)
  6. offset:轮廓点相对于原始图像对应点的偏移量,This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.

2、示例

代码如下

# encoding:utf-8

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

# 生成数据点
p_list = []
for x in range(150,155):
    for y in range(100, 200):
        p_list.append([x, y])
for x in range(100, 200):
    for y in range(150,155):
        p_list.append([x, y])

im_shape = [300,300]
im_ = np.zeros(im_shape,dtype=np.uint8)
for x,y in p_list:
    im_[x,y] = 255

mode = cv2.RETR_EXTERNAL
method = cv2.CHAIN_APPROX_SIMPLE
contours, hierarchy = cv2.findContours(im_, mode, method)
print(contours)

# 绘制点集和轮廓线
contours = np.squeeze(contours)
plt.scatter(np.array(p_list)[:,0],np.array(p_list)[:,1])
plt.plot(np.array(contours)[:,0],np.array(contours)[:,1],"r")
plt.show()

结果如下图所示,其中蓝色是数据点集,红颜色线条是点集外轮廓。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值