Finding holes in a binary image
<p>Assume we have following binary image</p>

<pre><code>0010
0101
0101
0010
0100
1010
0100
0000
</code></pre>

<p>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)</p>

<p>Here is some idea presented as code (and it might be not what you need).</p>

<p>The problem is, that i don't understand your example. Depending on the neighborhood-definition, there are different results possible.</p>

<ul>
<li>If you have a 8-neighborhood, all zeros are connected somehow (what does that mean about the surrounding 1's?).</li>
<li>If you have a 4-neighborhood, each one surrounded by 4 1's represents a new hole

<ul>
<li>Of course you could postprocess this but the question is still unclear</li>
</ul></li>
</ul>

<h3>Code</h3>

<pre><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 -&gt; 4 neighbors
label_vals = np.unique(labels)                      # conn=2 -&gt; 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)
</code></pre>

<h3>Output</h3>

<pre><code>('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
</code></pre>

java python algorithm binary-image