拆分2D numpy数组,可以进行不均匀的分割

kon*_*tin 3 python arrays numpy

我在python中有一个2D numpy数组,它对应于在for循环中计算的图像.阵列的大小是Nx40.我希望在循环的每个步骤中将初始数组拆分为大小为40x40(大约)的矩形数组.如果N不能除以40,那么最后一个图像应该包含剩余的除法.因此,例如87x40应为(40x40和47x40).到目前为止我做了什么:

div_num = spec.shape[0] / spec.shape[1]
remaining = spec.shape[0] % spec.shape[1]

lista = []
for i in range(1, div_num+1):
     img = spec[((i-1)*40):(i*40)][0:40]
     lista.append(img)
Run Code Online (Sandbox Code Playgroud)

如何在最后一张图片中添加剩余的行?

cs9*_*s95 6

你可以使用np.array_split哪些处理不均匀的分裂非常好.首先,我将初始化一些随机数组:

arr = np.random.randn(87, 40)
Run Code Online (Sandbox Code Playgroud)

接下来,计算要拆分的索引.如果形状arr可被40整除,则生成均匀分裂.否则,溢出进入第(n-1)个数组.

# compute the indices to split on
if arr.shape[0] % 40 == 0:
    split_idx = arr.shape[0] // 40
else:
    split_idx = np.arange(40, arr.shape[0], 40)[:-1]
Run Code Online (Sandbox Code Playgroud)

最后,打电话array_split,分开split_idx:

# split along the 0th axis
splits = np.array_split(arr, split_idx, axis=0)
Run Code Online (Sandbox Code Playgroud)

验证我们的阵列是否已正确分区:

[s.shape for s in splits]
[(40, 40), (47, 40)]
Run Code Online (Sandbox Code Playgroud)