最近在做一个项目需要删除掉一些小面积的噪点,考虑用连通域来实现,用到了 cv2.connectedComponentsWithStats这个函数,介绍一下
定义:
def connectedComponentsWithStats(image, labels=None, stats=None, centroids=None, connectivity=None, ltype=None): # real signature unknown; restored from __doc__
"""
connectedComponentsWithStats(image[, labels[, stats[, centroids[, connectivity[, ltype]]]]]) -> retval, labels, stats, centroids
. @overload
. @param image the 8-bit single-channel image to be labeled
. @param labels destination labeled image
. @param stats statistics output for each label, including the background label, see below for
. available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
. #ConnectedComponentsTypes. The data type is CV_32S.
. @param centroids centroid output for each label, including the background label. Centroids are
. accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
. @param ltype output image label type. Currently CV_32S and CV_16U are supported.
"""
pass
作用:
对一幅图像进行连通域提取,并返回找到的连通域的信息:retval、labels、stats、centroids
什么是连通域?
连通区域一般是指图像中具有相同像素值且位置相邻的前景像素点组成的图像区域。连通区域分析是指将图像中的各个连通区域找出并标记。
参数:
输入:
image:也就是输入图像,必须是二值图,即8位单通道图像。(因此输入图像必须先进行二值化处理才能被这个函数接受,比如说可以是canny检测得到的二值化图像,也可以是阈值化之后得到的二值化图像)
labels:指向被标记的图像
stats:每一个标记的统计信息输出,包括背景。可以通过打印stas(label, column)来查看每一个标记的信息。
centroids:每一个标记的中心位置。
connectivity:可选值为4或8,也就是使用4连通还是8连通。
ltype:输出图像标记的类型,目前支持CV_32S 和 CV_16U。
返回值:
retval:所有标记类型的数目
labels:图像上每一像素的标记,用数字1、2、3......表示
stats:每一个标记的统计信息,是一个5列的矩阵,每一行对应各个轮廓的x、y、width、height和面积,示例如下:
[ 176 142 92 3 93]
[ 278 143 150 3 151]
[ 430 144 370 7 372]centroids:连通域的中心点
一个简单的例子:
# Import the cv2 library
import cv2
# Read the image you want connected components of
src = cv2.imread('/test/image.bmp')
# Threshold it so it becomes binary
ret, thresh = cv2.threshold(src,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# You need to choose 4 or 8 for connectivity type
connectivity = 4
# Perform the operation
output = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)
# Get the results
# The first cell is the number of labels
num_labels = output[0]
# The second cell is the label matrix
labels = output[1]
# The third cell is the stat matrix
stats = output[2]
# The fourth cell is the centroid matrix
centroids = output[3]
至于还有一个函数cv2.connectedComponents,他们两个的区别可以参考一下下面的文章: