matchifang matchifang - 3 years ago 146
Python Question

How to order opencv connectedComponentewithStat by area?

From this question with the following code. Is there a way I can specify the function to return labels in order of largest area? If not, what would be the best method to get the index of the elements in order of descending value (from largest area to lowest) - if

has been converted to numpy array?

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

Answer Source

stats would be a 2D array with each row holding information about each blob and the last element holding the area of it. So, simply do the following to get the indices from max-area blob to min-area blob in descending order -

np.argsort(-stats[:,-1]) # or np.argsort(stats[:,-1])[::-1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download