您的位置:首页 > 运维架构

Opencv中cvFindContours函数使用

2013-07-29 21:24 821 查看


如上图,一共有6个contour(编号为0-5的椭圆)存放在contours中,对应的hierarchy与contour数目相同。contours中存放则每个contour的点。轮廓点的具体存放方式根据method变量的取值不同而不同。

根据len(contours),知道一共有多少个contour

len(contours[index]),知道第index个contour中一共有多少个点。

hierarchy是一个大小为 1 *  len(contour)* 4 的python array,里面存放的是各个contours的关系,等级、从属关系。hierarchy[0][i][0], hierarchy[0][i][1], hierarchy[0][i][2], hierarchy[0][i][3]分别表示第i个contour的next contour, previous contour, first child contour, parent contour。

上图为例:

1、当mode值对应为CV_RETR_TREE,其对应的值见下图



在Tree的等级分层情况下,上图被分为三个等级,分别以不同颜色表示,其中最上层为黑色,然后红、绿。其中3、4为1的chlid,3为1的first child,即1为3的parent。5又为3的first child等等,其next,和previous仅指向同一层的contour。以此类推。其树形结构为:



2、当mode值为CV_RETR_CCOMP时,只有两个等级,即连通域的外围边界(external boundaries of the components)为上层,次层为洞的内层边界(boundaries of the holes),如果holes中仍然有联通域,则认为此联通域边界为上层的外围边界。

在Ccomp的分层下,所有的next和previous指向同一层次的contour,即只有两层,理论上next中只有两个值为 -1,但实际情况并非如此,在上图中,0,1,2,5为top level,而3,4为second level,如果5中还有一个contour,则又是一个新的level,由于opencv只考虑了两层contour嵌套的情况,及1中嵌套3,3中嵌套5这种情况,而5中继续嵌套contour的情况,似乎没有考虑进去。由于没有考虑这种情况,所以嵌套较多时,仍会出现不止两个level。

3、当mode值为CV_RETR_LIST 时,存放所有轮廓,hierarchy没有任何作用,first child 和 parent 的值都为 -1。

4、当mode值为CV_CV_RETR_EXTERNAL 时,hierarchy也没有任何作用。其只存放最外层轮廓,若为上图,及为轮廓1,2,3.

对于参数method:

1、CV_CHAIN_APPROX_NONE 时,存放所有边界点,及内存中的任意相邻的两点,在图像上也是水平、垂直或斜对角相邻。

2、CV_CHAIN_APPROX_SIMPLE 时,压缩水平方向、垂直和斜对角方向的线段,仅存放endpoint。例如一个水平放置的矩形,其只存放四个顶点。 

import numpy as np
import cv2

img = cv2.imread('testcontours1.bmp')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE ,cv2.CHAIN_APPROX_SIMPLE)

print len(contours)
print len(contours[0])
print contours,'--------'
print hierarchy,'********'
output = np.zeros(img.shape,dtype = np.uint8)
cv2.drawContours(output, contours,-1,(0,255,0),2)
cv2.imshow('whole',output)
cv2.waitKey(0)
output[:] = 0

flag = [1,]*len(contours)
for i in range(len(contours)):
contour = contours[i].copy()
index = i
while flag[index] == 1:
cv2.drawContours(output, [contour],-1,(0,255,0),2) #contours is a list
flag[index] = 0
print index
index = hierarchy[0][index][0]  # dimension array
cv2.imshow('stepbystep',output)
cv2.waitKey(0)
if index == -1:
print index
break
else:
contour = contours[index]


测试图片:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息