如何在python中使用openCV的连接组件和stats?

Zac*_*opp 35 python opencv connected-components

我正在寻找一个如何在python中使用OpenCV的ConnectedComponentsWithStats()函数的示例,请注意,这仅适用于OpenCV 3或更高版本.官方文档仅显示了C++的API,即使在为python编译时该函数存在.我无法在网上找到它.

Zac*_*opp 84

该功能的工作原理如下:

# 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]
Run Code Online (Sandbox Code Playgroud)

标签是输入图像大小的矩阵,其中每个元素的值等于其标签.

统计数据是函数计算的统计数据的矩阵.它的长度等于标签数量,宽度等于统计数量.它可以与OpenCV文档一起使用:

每个标签的统计输出,包括背景标签,请参阅下面的可用统计信息.统计数据通过统计数据[label,COLUMN]访问 ,其中可用列定义如下.

  • cv2.CC_STAT_LEFT最左边的(x)坐标,它是水平方向上包含框的包含性开始.
  • cv2.CC_STAT_TOP最上面的(y)坐标,它是垂直方向上边界框的包含性开始.
  • cv2.CC_STAT_WIDTH边界框的水平大小
  • cv2.CC_STAT_HEIGHT边界框的垂直大小
  • cv2.CC_STAT_AREA连接组件的总面积(以像素为单位)

质心是一个矩阵,每个质心的x和y位置.该矩阵中的行对应于标签号.

  • 有人可以解释一下如何使用标签吗?如何检查质心是否是哪个标签? (2认同)
  • 图像中的每个组件都有一个数字(标签).背景是标签0,附加对象从1到`num_labels-1`编号.质心的编号与标签的编号相同.`centroids [0]`不是特别有用 - 它只是背景.`centroids [1:num_labels]`就是你想要的. (2认同)
  • @matchifang 您可以创建一个包含组件区域的数组:`areas=output[2][:,4]` 然后是一个包含组件数量的数组:`nr=np.arange(output[0])` 然后对它们进行排序根据区域大小:`ranked=sorted(zip(areas,nr))` 来自这里的帮助:/sf/ask/463296081/ (2认同)

Dan*_*rez 14

我来过这里几次来记住它是如何工作的,每次我都必须将上面的代码简化为:

_, thresh = cv2.threshold(src,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
connectivity = 4  # You need to choose 4 or 8 for connectivity type
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh , connectivity , cv2.CV_32S)
Run Code Online (Sandbox Code Playgroud)

希望对大家有用:)


Bar*_*evy 6

补充一下Zack Knopp,如果您使用的是灰度图像,则可以简单地使用:

import cv2
import numpy as np

src = cv2.imread("path\\to\\image.png", 0)
binary_map = (src > 0).astype(np.uint8)
connectivity = 4 # or whatever you prefer

output = cv2.connectedComponentsWithStats(binary_map, connectivity, cv2.CV_32S)
Run Code Online (Sandbox Code Playgroud)

当我尝试Zack Knopp在灰度图像上使用答案时,它不起作用,这就是我的解决方案。