问题描述
我正在寻找有关如何在python中使用OpenCV的ConnectedComponentsWithStats()函数的示例,请注意,这仅在OpenCV 3或更高版本中可用.官方文档仅显示用于C ++的API,即使该函数在为python编译时也存在.我在网上找不到它.
I am looking for an example of how to use OpenCV's ConnectedComponentsWithStats() function in python, note this is only available with OpenCV 3 or newer. The official documentation only shows the API for C++, even though the function exists when compiled for python. I could not find it anywhere online.
推荐答案
该函数的工作方式如下:
The function works as follows:
# Import the cv2 library
import cv2
# Read the image you want connected components of
src = cv2.imread('/directorypath/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]
标签是一个输入图像大小的矩阵,其中每个元素的值都等于其标签.
Labels is a matrix the size of the input image where each element has a value equal to its label.
统计数据是该函数计算的统计数据的矩阵.它的长度等于标签数,宽度等于统计数.它可以与OpenCV文档一起使用:
Stats is a matrix of the stats that the function calculates. It has a length equal to the number of labels and a width equal to the number of stats. It can be used with the OpenCV documentation for it:
- cv2.CC_STAT_LEFT :最左侧(x)坐标,即水平方向上边界框的包含端.
- cv2.CC_STAT_TOP 最高(y)坐标,它是垂直方向上边界框的包含端.
- cv2.CC_STAT_WIDTH 边框的水平尺寸
- cv2.CC_STAT_HEIGHT 边框的垂直大小
- cv2.CC_STAT_AREA 所连接组件的总面积(以像素为单位)
- cv2.CC_STAT_LEFT The leftmost (x) coordinate which is the inclusive start of the bounding box in the horizontal direction.
- cv2.CC_STAT_TOP The topmost (y) coordinate which is the inclusive start of the bounding box in the vertical direction.
- cv2.CC_STAT_WIDTH The horizontal size of the bounding box
- cv2.CC_STAT_HEIGHT The vertical size of the bounding box
- cv2.CC_STAT_AREA The total area (in pixels) of the connected component
质心是一个矩阵,其中每个质心的x和y位置.此矩阵中的行对应于标签号.
Centroids is a matrix with the x and y locations of each centroid. The row in this matrix corresponds to the label number.
这篇关于如何在python中将openCV的连接组件与统计信息一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!