11

I am on Ubuntu, python 2.7. Working with OpenCV.

I was trying to understand exactly what the function cv2.connectedComponents is doing. This is the image:

enter image description here

The code:

import cv2
import numpy as np

img = cv2.imread('BN.tif', 0)

img = np.uint8(img)
_, markers = cv2.connectedComponents(img)
 

From what I understood, this funtion creates an array with same size than the provided image. For each component detected assign the same number for all the (y,x) positions for that component. If the background is all '0', then the circle would be all '1', the next square all '2', etc. The last component should be all '19'. I am reading the numbers of components by getting the highest number defining a component:

np.amax(markers)

I should get the 19, but I am getting 1.

My question: why I am getting only 1 component?

Community
  • 1
  • 1
daniel_hck
  • 1,100
  • 3
  • 19
  • 38

1 Answers1

12

This is because cv2.connectedComponents() considers only the white portion as a component. Hence you are getting a single component.

You have to invert your image. You can do so by using cv2.bitwise_not() function.

CODE:

import cv2
import numpy as np

img = cv2.imread('cc.png', 0)
ret, thresh = cv2.threshold(img, 127, 255, 0)

#---- Inverting the image here ----
img = cv2.bitwise_not(thresh)     
_, markers = cv2.connectedComponents(img)
print np.amax(markers)

RESULT:

19
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
  • 1
    YEs, you are right. Thank you to Miki and Jeru Luke for the right answers. Now it works. – daniel_hck Apr 21 '17 at 16:28
  • 4
    It would seem to me more logical to use `cv2.THRESH_BINARY_INV` as the type rather than thresholding and then inverting. – beaker Apr 21 '17 at 17:51
  • 1
    @beaker Point well noted. But the highlight of this question was to find the connected components upon inversion. So that is why I actually wrote an extra line to highlight image inversion – Jeru Luke Apr 21 '17 at 17:55
  • 1
    for python3 change last line to print(np.max(markers)) – Rahul May 16 '20 at 04:11