Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cv2.connectedComponents not detecting components

Tags:

python

opencv

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?

like image 242
daniel_hck Avatar asked Apr 21 '17 16:04

daniel_hck


1 Answers

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
like image 180
Jeru Luke Avatar answered Oct 18 '22 22:10

Jeru Luke