2

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 stats 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]
matchifang
  • 5,190
  • 12
  • 47
  • 76

1 Answers1

3

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]
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • my bad. I will delete the comment and edit to avoid confusion. I have marked the question as accepted. Thanks :) – matchifang Jul 24 '17 at 21:31
  • do you know if the first index will alway be 0, meaning the connected component is the whole image? – matchifang Jul 24 '17 at 21:46
  • @matchifang I am not really sure about the pattern of `stats` output. It seems its a big number always. Do you want to omit the first row and get the ordered array? – Divakar Jul 24 '17 at 21:59
  • that is fine. I can't find it in the docs, so I thought you might know, but I can just exclude index 0. Thank you :) – matchifang Jul 24 '17 at 22:01
  • @matchifang 0 is the background label. So you _must_ exclude it if you want to consider only foreground labels – Miki Jul 24 '17 at 23:44