如何在Python中使用OpenCV的connectedComponentsWithStats?

l7mqbcuq  于 2022-11-15  发布在  Python
关注(0)|答案(4)|浏览(205)

我正在寻找一个如何在Python中使用OpenCV的connectedComponentsWithStats()函数的例子。注意,这只在OpenCV 3或更高版本中可用。官方文档只显示了C++的API,即使该函数在编译为Python时也存在。我在网上找不到它。

kcugc4gi

kcugc4gi1#

函数的工作方式如下:

  1. # Import the cv2 library
  2. import cv2
  3. # Read the image you want connected components of
  4. src = cv2.imread('/directorypath/image.bmp')
  5. # Threshold it so it becomes binary
  6. ret, thresh = cv2.threshold(src,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
  7. # You need to choose 4 or 8 for connectivity type
  8. connectivity = 4
  9. # Perform the operation
  10. output = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)
  11. # Get the results
  12. # The first cell is the number of labels
  13. num_labels = output[0]
  14. # The second cell is the label matrix
  15. labels = output[1]
  16. # The third cell is the stat matrix
  17. stats = output[2]
  18. # The fourth cell is the centroid matrix
  19. centroids = output[3]

标签是一个输入图像大小的矩阵,其中每个元素的值等于其标签。
Stats是函数计算的统计信息矩阵。它的长度等于标签的数量,宽度等于统计信息的数量。它可以与OpenCV文档一起使用:

每个标签(包括背景标签)的统计信息输出,有关可用的统计信息,请参阅下面的内容。通过**stats[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位置的矩阵。此矩阵中的行对应于标签编号。

展开查看全部
utugiqy6

utugiqy62#

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

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

希望它对每个人都有用:)

u3r8eeie

u3r8eeie3#

添加到Zack Knopp答案,如果您使用的是灰度图像,您可以简单地用途:

  1. import cv2
  2. import numpy as np
  3. src = cv2.imread("path\\to\\image.png", 0)
  4. binary_map = (src > 0).astype(np.uint8)
  5. connectivity = 4 # or whatever you prefer
  6. output = cv2.connectedComponentsWithStats(binary_map, connectivity, cv2.CV_32S)

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

8cdiaqws

8cdiaqws4#

输入图像需要是单通道的。所以首先转换为灰度,否则会导致opencv 4.x中的错误,您需要转换为灰度,然后Zack的答案。

  1. src = cv.cvtColor(src, cv.COLOR_BGR2GRAY)

相关问题