12

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?

2
  • 4
    Because the foreground objects should be white, and the background black. Invert the image! img = 255 - img; Commented Apr 21, 2017 at 16:19
  • Ouch... how can I be so... Thats correct! thanks Commented Apr 21, 2017 at 16:25

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

4 Comments

YEs, you are right. Thank you to Miki and Jeru Luke for the right answers. Now it works.
It would seem to me more logical to use cv2.THRESH_BINARY_INV as the type rather than thresholding and then inverting.
@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
for python3 change last line to print(np.max(markers))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.