My goal is to count objects in a binary array, using Python. I am applying the scikit-image measure.label, to to count objects(should be 1's) in the the array, despite reading the documentation-link, I am getting results that cannot be explained.
a=np.array(np.matrix('0 1 0 0 1;0 1 0 0 0; 0 0 0 0 0;0 0 0 0 1'))
print(a)
img=measure.label(a)
propsa = measure.regionprops(img)
length = len(propsa)
print ('length='+str(length))
for label in propsa:
print (label.centroid)
>>>
[[0 1 0 0 1]
[0 1 0 0 0]
[0 0 0 0 0]
[0 0 0 0 1]]
length=3
(0.5, 1.0)
(0.0, 4.0)
(3.0, 4.0)
When background is selected to be zero,
a=np.array(np.matrix('0 1 0 0 1;0 1 0 0 0; 0 0 0 0 0;0 0 0 0 1'))
print(a)
img=measure.label(a, background=0)
propsa = measure.regionprops(img)
length = len(propsa)
print ('length='+str(length))
for label in propsa:
print (label.centroid)
>>>
[[0 1 0 0 1]
[0 1 0 0 0]
[0 0 0 0 0]
[0 0 0 0 1]]
length=2
(0.0, 4.0)
(3.0, 4.0)
Why is there inconsistent? From my understanding the label function labels "0" as -1 background?!
Following question It appears that measure.label of the CSV file example counts two objects a large one and its cavity. Sure enough when I inquiry the coordinates of the cavity of img I get a value of 2. Which means the cavity is the second object. Why is an aggregate of zeros counted as an object, and is there away around it?
length=2
(214.23444957510378, 505.25546156532539)
(238.77173913043478, 740.28260869565213)
>>> img[238,740]
2
>>>
skimage.measure.label's convention of labelling 'background' pixels as -1, another option would be to usescipy.ndimage.label. It does essentially the same thing, but always treats zeros in the input array as background, and assigns them a label of zero in the output.