11
votes

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?

1
Because the foreground objects should be white, and the background black. Invert the image! img = 255 - img; - Miki
Ouch... how can I be so... Thats correct! thanks - daniel_hck

1 Answers

12
votes

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