(在python3中)如何从以每个元素为中心的m-by-n数组中提取几个n-by-m块
例如,在9×9矩阵中,使用3×3块,我需要在矩阵的每个位置提取块。这里的挑战(对我来说)是因为他各自区块内的I,J元素改变了位置
在这里,我展示了一个9乘9矩阵的9个块(9个位置)(当然有81个块要提取)
下面的代码(仅适用于)在拐角处非常有效。在这里,块的大小(WSIWS按WSIZE)是奇数,以便在中间找到索引(eindex(0),eindex 1)。p>
def windowing(array,Wsize,Eindex):
'''
Extract an sub-array of array for the element located in the index 'Eindex'.
Wsize-by-Wsize is the shape of the window
'''
block=np.zeros(tuple(Wsize))
k0 = int((Wsize[0]-1)/2)
k1 = int((Wsize[1]-1)/2)
s0 = Wsize[0]
s1 = Wsize[1]
I = array.shape[0]-1 # las index in i-direction
J = array.shape[1]-1 # las index in i-direction
if (Eindex[0]==0) and (Eindex[1]==0):
block=array[0:Eindex[0]+s0,0:Eindex[1]+s1]
return block
elif (Eindex[0]==I) and (Eindex[1]==0):
block=array[-s0:,0:Eindex[1]+s1]
return block
elif (Eindex[0]==0) and (Eindex[1]==J):
block=array[0:Eindex[0]+s0,-s1:]
return block
elif (Eindex[0]==I) and (Eindex[1]==J):
block=array[-s0:,-s1:]
return block
例如,检查:
x = np.arange(81).reshape(9,9)
print(windowing(x,[3,3],[0,0]))
print(windowing(x,[3,3],[8,8))
print(windowing(x,[3,3],[8,0]))
print(windowing(x,[3,3],[0,8]))
这是一种采用任意数组、坐标和窗口大小的方法
测试用例:
您可以像这样使用
numpy
:请阅读numpy的docs了解更多信息
我编辑了代码,所以现在它可以工作了
相关问题 更多 >
编程相关推荐