I'm searching a way to select "pixels" in an array using a structuring element: Imagine we have that array a, and that structuring element s,
a=np.array([[ 0, 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12, 13],
[14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34],
[35, 36, 37, 38, 39, 40, 41],
[42, 43, 44, 45, 46, 47, 48]])
s=np.array([[0,1,0],
[1,1,1],
[0,1,0]])
I'm then searching for a function that will act like
f(a, position=(3,3), structure=s) = [17,23,24,25,31]
It looks like scipy.ndimage morphology functions can do that internally. A workaround would be to create a np.zeros array with the same shape as a, put a 1 at a position of interest and the dilate it, but that would be very resource consuming - especially since my arrays are not 7 * 7.
Here is an answer using view_as_windows
(which uses numpy strides under the hood):
from skimage.util import view_as_windows
def f(a, position, structure):
return view_as_windows(a,structure.shape)[tuple(np.array(position)-1)][structure.astype(bool)]
output:
f(a, position=(3,3), structure=s)
#[17 23 24 25 31]
if you feed the position
as numpy array instead of tuple and structure
as boolean array instead of int, the answer will even be shorter since you will not need conversions:
def f(a, position, structure):
return view_as_windows(a,structure.shape)[tuple(position-1)][structure]
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.