Janek Nikicicz - 1 year ago 69

Python Question

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).

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.

A minimal example would be as follows:

ArrayA:

`[ 1 1 0 ]`

[ 1 0 0 ]

[ 0 1 1 ]

ArrayB:

`[ 1 0 0 ]`

[ 1 1 0 ]

[ 0 1 1 ]

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

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.

I was thinking of something along the lines of

`np.where(arrayA == 0 and arrayB == 0)`

but that doesn't work.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can use a simple comparison with a logical and:

```
>>> A
array([[1, 1, 0],
[1, 0, 0],
[0, 1, 1]])
>>> B
array([[1, 0, 0],
[1, 1, 0],
[0, 1, 1]])
>>> np.logical_and(A == 0, B == 0)
array([[False, False, True],
[False, False, True],
[ True, False, False]], dtype=bool)
```

And use `np.where()`

and `column_stack()`

in order to get the indices of the intended items:

```
>>> np.column_stack(np.where(np.logical_and(A == 0, B == 0)))
array([[0, 2],
[1, 2],
[2, 0]])
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**