Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何按区域订购opencv ConnectedComponentWithStat?_Python_Opencv_Numpy - Fatal编程技术网

Python 如何按区域订购opencv ConnectedComponentWithStat?

Python 如何按区域订购opencv ConnectedComponentWithStat?,python,opencv,numpy,Python,Opencv,Numpy,使用以下代码从问题中删除。是否有一种方法可以指定函数以按最大面积的顺序返回标签?如果不是,如果stats已转换为numpy数组,那么按降序(从最大区域到最小区域)获取元素索引的最佳方法是什么 # Import the cv2 library import cv2 # Read the image you want connected components of src = cv2.imread('/directorypath/image.bmp') # Threshold it so it be

使用以下代码从问题中删除。是否有一种方法可以指定函数以按最大面积的顺序返回标签?如果不是,如果
stats
已转换为numpy数组,那么按降序(从最大区域到最小区域)获取元素索引的最佳方法是什么

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

stats
将是一个
2D
数组,每一行包含每个blob的信息,最后一个元素包含该blob的区域。因此,只需执行以下操作,即可按降序从
max area
blob到
min area
blob获取索引-

np.argsort(-stats[:,-1]) # or np.argsort(stats[:,-1])[::-1]

我的错。我将删除评论并进行编辑以避免混淆。我已将该问题标记为已接受。谢谢:)你知道第一个索引是否总是0,这意味着连接的组件就是整个图像吗?@matchifang我不确定
stats
输出的模式。这似乎总是一个很大的数字。是否要省略第一行并获取有序数组?这很好。我在文档中找不到它,所以我想您可能知道,但我可以排除索引0。谢谢:)@matchifang 0是背景标签。因此,如果您只考虑前景标签,则必须排除它。