如何在python中使用带有统计信息的openCV的连接组件? [英] How to use openCV's connected components with stats in python?

查看:54
本文介绍了如何在python中使用带有统计信息的openCV的连接组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找如何在 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.

推荐答案

功能如下:

# 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.

Stats 是函数计算的统计数据的矩阵.它的长度等于标签的数量,宽度等于统计数据的数量.它可以与 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:

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

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 最左边的 (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的连接组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆