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:
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With