简体   繁体   中英

What is the most pythonic way to find all coordinate pairs in a numpy array that match a specific condition?

So given a 2d numpy array consisting of ones and zeros, I want to find every index where it is a value of one and where either to its top, left, right, or bottom consists of a zero. For example in this array

0 0 0 0 0   
0 0 1 0 0   
0 1 1 1 0  
0 0 1 0 0  
0 0 0 0 0  

I only want coordinates for (1,2), (2,1), (2,3) and (3,2) but not for (2,2).

I have created code that works and creates two lists of coordinates, similar to the numpy nonzero method, however I don't think its very "pythonic" and I was hoping there was a better and more efficient way to solve this problem. (*Note this only works on arrays padded by zeros)

from numpy import nonzero
...
array= ... # A numpy array consistent of zeros and ones
non_zeros_pairs=nonzero(array)
coordinate_pairs=[[],[]]
for x, y in zip(temp[0],temp[1]):
    if array[x][y+1]==0 or array[x][y-1]==0 or array[x+1][y]==0 or array[x-1][y]==0:
             coordinate_pairs[0].append(x)
             coordinate_pairs[1].append(y)
...

If there exist methods in numpy that can handle this for me, that would be awesome. If this question has already been asked/answered on stackoverflow before, I will gladly remove this, I just struggled to find anything. Thank You.

Setup

import scipy.signal
import numpy as np

a = np.array([[0, 0, 0, 0, 0],
              [0, 0, 1, 0, 0],
              [0, 1, 1, 1, 0],
              [0, 0, 1, 0, 0],
              [0, 0, 0, 0, 0]])

Create a window which matches the four directions from each value, and convolve . Then, you can check if elements are 1 , and if their convolution is less than 4 , since a value ==4 means that the value was surrounded by 1s

window = np.array([[0, 1, 0],
                   [1, 0, 1],
                   [0, 1, 0]])

m = scipy.signal.convolve2d(a, window, mode='same', fillvalue=1)

v = np.where(a & (m < 4))

list(zip(*v))

[(1, 2), (2, 1), (2, 3), (3, 2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM