加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 10:35:21 所属栏目:Python 来源:网络整理
导读:我正在寻找一个如何在 python中使用OpenCV的ConnectedComponentsWithStats()函数的示例,请注意,这仅适用于OpenCV 3或更高版本.官方文档仅显示C的API,即使在为python编译时该函数存在.我无法在网上找到它. 解决方法 该功能的工作原理如下: # Import the cv2
我正在寻找一个如何在 python中使用OpenCV的ConnectedComponentsWithStats()函数的示例,请注意,这仅适用于OpenCV 3或更高版本.官方文档仅显示C的API,即使在为python编译时该函数存在.我无法在网上找到它.

解决方法

该功能的工作原理如下:

# 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,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]

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

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

Statistics output for each label,including the background label,see
below for available statistics. Statistics are accessed via
stats[label,COLUMN] where available columns are defined below.

  • 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位置.该矩阵中的行对应于标签号.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读