starry night
starry night

Reputation: 23

python/numpy: find edges of a 2D/3D mask

This question is very similar to this question but I am not sure how to apply the answer on 2D or 3D arrays.

For a simple example, using the following 2 dimensional array of shape (5,5):

In [158]: a                                                                                                                                                                      
Out[158]: 
array([[0, 0, 0, 0, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0]])

I want to get the indices of the edges. For this case:

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

Right now I shift the array in both directions/axes, compare to the original array and identify the cells that have different values:

In [230]: np.nonzero(a!= np.roll(a,shift=(1,1),axis=(0,1)))                                                                                                                      
Out[230]: (array([1, 1, 1, 2, 2, 3, 3, 4, 4, 4]), array([1, 2, 3, 1, 4, 1, 4, 2, 3, 4]))

Some of the indices are correct but some others not. I guess that the 4s should become 3s because of the shifts I applied but I am not sure how to correct this since I am planning to apply this to much more complicated (and bigger) mask arrays. My final goal is to apply this to 3D arrays.

I am using Python 3.7.1

Upvotes: 2

Views: 2323

Answers (1)

Michael Szczesny
Michael Szczesny

Reputation: 5036

You can convolve your array with an edge detection filter

import numpy as np
from scipy.ndimage import convolve

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

fil = [[-1,-1,-1],
       [-1, 8,-1],
       [-1,-1,-1]]

np.where(convolve(x,fil, mode='constant') > 1)

Out:

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

The result of the convolution

convolve(x,fil, mode='constant')

Out:

[[-1 -2 -3 -2 -1]
 [-2  5  3  5 -2]
 [-3  3  0  3 -3]
 [-2  5  3  5 -2]
 [-1 -2 -3 -2 -1]]

Upvotes: 1

Related Questions