[英]Select pixels in an array using a structuring element in python 3
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,我正在使用结构元素在数组中搜索 select 个“像素”的方法:假设我们有数组 a 和结构元素 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然后我正在寻找一个 function 就像
f(a, position=(3,3), structure=s) = [17,23,24,25,31]
It looks like scipy.ndimage morphology functions can do that internally.看起来 scipy.ndimage 形态学函数可以在内部完成。 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.
一种解决方法是创建一个与 a 形状相同的 np.zeros 数组,将 1 放在感兴趣的 position 上并对其进行扩张,但这会非常耗费资源——尤其是因为我的 arrays 不是 7 * 7。
Here is an answer using view_as_windows
(which uses numpy strides under the hood):这是使用
view_as_windows
的答案(它在引擎盖下使用 numpy 步幅):
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: 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:如果将
position
作为 numpy 数组而不是元组,将structure
作为 boolean 数组而不是 int,答案甚至会更短,因为您不需要转换:
def f(a, position, structure):
return view_as_windows(a,structure.shape)[tuple(position-1)][structure]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.