python - 使用python 3中的结构元素选择数组中的像素
问题描述
我正在寻找一种使用结构元素在数组中选择“像素”的方法:假设我们有那个数组 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]])
然后我正在寻找一个像
f(a, position=(3,3), structure=s) = [17,23,24,25,31]
看起来 scipy.ndimage 形态函数可以在内部做到这一点。一种解决方法是创建一个与 a 形状相同的 np.zeros 数组,将 1 放在感兴趣的位置并扩大它,但这会非常消耗资源 - 特别是因为我的数组不是 7 * 7。
解决方案
这是一个使用view_as_windows
(在引擎盖下使用 numpy strides)的答案:
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)]
输出:
f(a, position=(3,3), structure=s)
#[17 23 24 25 31]
如果您将position
作为 numpy 数组而不是 tuple 和structure
作为布尔数组而不是 int 提供,则答案甚至会更短,因为您不需要转换:
def f(a, position, structure):
return view_as_windows(a,structure.shape)[tuple(position-1)][structure]
推荐阅读
- python - 使用 scipy.interpolate.RBFInterpolator 进行 Python 2D 插值
- r - 使用带有命名样本的数据框时出现 R 错误 - “termlabels”必须是长度至少为 1 的字符向量
- swift - 使用 OptionSet 的便捷方式是什么?
- maven - Android Studio 使用 http 版本的 mavenCentral
- spring - 指定自定义 ObjectMapper 时忽略 spring.json.type.mapping 属性
- windows - 如何在 docker compose yml 文件中设置等效的“docker run -m 2048”
- flutter - Flutter RawKeyboardListener
- laravel - 为什么我在 repo 重置后收到 Forge Laravel 505 服务器错误
- ios - 如何从 iOS 设置应用程序启动应用程序?
- visual-studio-2019 - 如何在 Visual Studio 2019 中关闭自动重命名?