首页 > 解决方案 > 将 numpy 3-d 数组拆分为较小 3-d 数组的 2-d 数组

问题描述

我目前将图像作为具有 3 个通道(RGB)的 numpy 数组。我想将其有效地拆分为一个由较小的 3-d 子数组组成的 2-d 数组。例如,如果我的图像形状为 (100, 100, 3),我想将其转换为 10 x 10 数组,其中元素是 (10, 10, 3) 图像(子图像),同时保持空间方向。图像的高度和宽度将始终相等。

我也想扭转整个操作。

如果这很难做到,有没有办法将其转换为行或列顺序的 4-d 数组,而元素仍然相同?

有没有一种有效的方法可以使用 numpy 方法来做到这一点?

标签: pythonarraysnumpy

解决方案


您可以使用 strides 来拆分数组:

image = np.arange(30000).reshape(100,100,3)

sub_shape = (10,10,3)

#divide the matrix into sub_matrices of subshape
view_shape = tuple(np.subtract(image.shape, sub_shape) + 1) + sub_shape
strides = image.strides + image.strides
sub_matrices = np.squeeze(np.lib.stride_tricks.as_strided(image,view_shape,strides)[::sub_shape[0],::sub_shape[1],:])

sub_matrices形状:

(10, 10, 10, 10, 3)

sub_matrices[i,j,:,:,:][i,j]第-个子数组。

或者,您可以重塑图像:

sub_shape = (10,10,3)
sub_matrices = np.swapaxes(image.reshape(image.shape[0]/sub_shape[0],sub_shape[0],image.shape[1]/sub_shape[1],sub_shape[1],image.shape[3]), 1, 2)

sub_matrices[i,j,:,:,:]是第[i,j]-th 个子数组。


推荐阅读