Calculate number of equal neighbouring cells within a numpy array
<p>I have 2d binary <code>numpy</code> <code>arrays</code> of varying size, which contain certain patterns. 
Just like this:</p>

<pre><code>import numpy
a = numpy.zeros((6,6), dtype=numpy.int)
a[1,2] = a[1,3] = 1
a[4,4] = a[5,4] = a[4,3] = 1
</code></pre>

<p>Here the "image" contains two patches one with 2 and one with 3 <em>connected</em> cells. </p>

<pre><code>print a
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 1, 0],
       [0, 0, 0, 0, 1, 0]])
</code></pre>

<p><br>
I want to know how often a non-zero cell borders another non-zero cell ( <strong>neighbours defined as rook's case</strong>, so the cells to the left, right, below and above each cell) including their pseudo-replication (so vice-versa).</p>

<p>A previous <a href="https://stackoverflow.com/questions/13443246/calculate-perimeter-of-numpy-array">approach</a> for inner boundaries returns wrong values (5) as it was intended to calculate outer boundaries.</p>

<pre><code>numpy.abs(numpy.diff(a, axis=1)).sum()
</code></pre>

<p>So for the above test array, the correct total result would be <strong>6</strong> (The upper patch has two internal borders, the lower four ).</p>

<p>Grateful for any tips! </p>

<p>EDIT:</p>

<ul>
<li><p>Mistake: The lower obviously has 4 internal edges (neighbouring cells with the same value)</p></li>
<li><p>Explained the desired neighbourhood a bit more</p></li>
</ul>