Assume we have following binary image
0010
0101
0101
0010
0100
1010
0100
0000
0 represents background pixels and 1 represents image pixels.As you can see there are two holes in this image.Is there a way to obtain the number of holes in this image using algorithms?(Java or Python but not Matlab)
Here is some idea presented as code (and it might be not what you need).
The problem is, that i don't understand your example. Depending on the neighborhood-definition, there are different results possible.
import numpy as np
from skimage.measure import label
img = np.array([[0,0,1,0],
[0,1,0,1],
[0,1,0,1],
[0,0,1,0],
[0,1,0,0],
[1,0,1,0],
[0,1,0,0],
[0,0,0,0]])
labels = label(img, connectivity=1, background=-1) # conn=1 -> 4 neighbors
label_vals = np.unique(labels) # conn=2 -> 8 neighbors
counter = 0
for i in label_vals:
indices = np.where(labels == i)
if indices:
if img[indices][0] == 0:
print('hole: ', indices)
counter += 1
print(img)
print(labels)
print(counter)
('hole: ', (array([0, 0, 1, 2, 3, 3, 4]), array([0, 1, 0, 0, 0, 1, 0])))
('hole: ', (array([0]), array([3])))
('hole: ', (array([1, 2]), array([2, 2])))
('hole: ', (array([3, 4, 4, 5, 6, 6, 6, 7, 7, 7, 7]), array([3, 2, 3, 3, 0, 2, 3, 0, 1, 2, 3])))
('hole: ', (array([5]), array([1])))
[[0 0 1 0]
[0 1 0 1]
[0 1 0 1]
[0 0 1 0]
[0 1 0 0]
[1 0 1 0]
[0 1 0 0]
[0 0 0 0]]
[[ 1 1 2 3]
[ 1 4 5 6]
[ 1 4 5 6]
[ 1 1 7 8]
[ 1 9 8 8]
[10 11 12 8]
[ 8 13 8 8]
[ 8 8 8 8]]
5