Counting overlapping values of two 2D binary numpy arrays for a specific value
<p>I start with two images of the same size. I convert them to binary black/white numpy arrays (0 = black 1 = white). I'd like to find how many of the black pixels overlap (0 value at same position in both arrays).</p>

<p>I know how to do this with for loops, but I'm trying to learn how to use numpy properly, and I imagine there's a much better way of doing this.</p>

<p>A minimal example would be as follows:</p>

<p>ArrayA:</p>

<pre><code>[ 1 1 0 ]
[ 1 0 0 ]
[ 0 1 1 ]
</code></pre>

<p>ArrayB:</p>

<pre><code>[ 1 0 0 ]
[ 1 1 0 ]
[ 0 1 1 ]
</code></pre>

<p>I want to know how many times both arrays have a '0' value in the same position.</p>

<p>In this case, once in the 1st row 3rd column, once in the 2nd rows 3rd column, and once in the 3rd row 1st column. Total overlap of '0' values: 3.</p>

<p>I was thinking of something along the lines of</p>

<pre><code>np.where(arrayA == 0 and arrayB == 0)
</code></pre>

<p>but that doesn't work.</p>

<p>You can use a simple comparison with a logical and:</p>

<pre><code>&gt;&gt;&gt; A
array([[1, 1, 0],
       [1, 0, 0],
       [0, 1, 1]])
&gt;&gt;&gt; B
array([[1, 0, 0],
       [1, 1, 0],
       [0, 1, 1]])
&gt;&gt;&gt; np.logical_and(A == 0, B == 0)
array([[False, False,  True],
       [False, False,  True],
       [ True, False, False]], dtype=bool)
</code></pre>

<p>And use <code>np.where()</code> and <code>column_stack()</code> in order to get the indices of the intended items:</p>

<pre><code>&gt;&gt;&gt; np.column_stack(np.where(np.logical_and(A == 0, B == 0)))
array([[0, 2],
       [1, 2],
       [2, 0]])
</code></pre>

<p>Or as a pretty Numpythonic way as suggested in comment use <code>np.argwhere</code>:</p>

<pre><code>&gt;&gt;&gt; np.argwhere(np.logical_and(A == 0, B == 0))
array([[0, 2],
       [1, 2],
       [2, 0]])
</code></pre>

python arrays numpy multidimensional-array