Search code examples
opencvconnected-componentspython

Strange behaviour of connectedComponenentsWithStat in opencv 4.4.0


This is my 8bit image: enter image description here

I try to load it with cv2 and split into connected components:

seg_r=cv2.imread("seg_r.png",0)
seg_num_labels, seg_labels, seg_stats, seg_centroids = cv2.connectedComponentsWithStats(seg_r)
print(seg_stats)

I get only 2 huge connected components, i.e:

[[      0       0    1260    1623   33236]
 [      0       0    1259    1622 2011744]]

(I also tried to make black border around image, with no success). Why is this?


Solution

  • As explained in the documentation, you should use a binary image:

    computes the connected components labeled image of boolean image

    This means that all pixels with value==0 are considered as background, while all pixels with value>0 are foreground.

    In your image you probably have all foreground pixels connected, so you end up with only two labels.