我有一个 3D numpy 体积和一个 2D numpy 矩阵:
foo = np.random.rand(20,20,10)
amin = np.argmin(foo, axis=2)
我想使用 amin
变量以与 np.min
相同的方式对体积进行切片:
grid = np.indices(min.shape)
idcs = np.stack([grid[0], grid[1], min])
fmin = foo[idcs[0], idcs[1], idcs[2]]
问题是我不能使用 np.min
因为我还需要 amin
邻居来进行插值,我会做的事情:
pre = foo[idcs[0], idcs[1], np.clip(idcs[2]-1, 0, 9)]
post = foo[idcs[0], idcs[1], np.clip(idcs[2]+1, 0, 9)]
是否有更 pythonic (nupyic) 的方式来做到这一点而不创建 np.grid
?像这样的东西:
foo[:,:,amin-1:amin+1]
这确实有效(我会关心早期填充的 margin 处理)
最佳答案
您可以使用 np.ogrid
而不是 np.indices
来节省内存。
np.ogrid
返回一个“开放的”网格:
In [24]: np.ogrid[:5,:5]
Out[24]:
[array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]])]
ogrid
返回可用作索引的组件数组
与使用 np.indices
的方式相同。
当它们用作索引时,NumPy 将自动广播开放网格中的值:
In [49]: (np.indices((5,5)) == np.broadcast_arrays(*np.ogrid[:5, :5])).all()
Out[49]: True
import numpy as np
h, w, d = 20, 20, 10
foo = np.random.rand(h, w, d)
amin = np.argmin(foo, axis=2)
X, Y = np.ogrid[:h, :w]
amins = np.stack([np.clip(amin+i, 0, d-1) for i in [-1, 0, 1]])
fmins = foo[X, Y, amins]
最好将fmin
、pre
和post
存储在一个数组中,fmins
,
因为某些 NumPy/Scipy 操作(如 argmin
或 griddata
)可能需要一个数组中的值。如果稍后您需要单独操作这 3 个组件,您始终可以使用 fmins[i]
或定义
pre, fmin, post = fmins
关于python - Numpy:使用矩阵切片体积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53520411/