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.
- If you have a 8-neighborhood, all zeros are connected somehow (what does that mean about the surrounding 1's?).
- If you have a 4-neighborhood, each one surrounded by 4 1's represents a new hole
- Of course you could postprocess this but the question is still unclear
Code
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)
Output
('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