[英]Split numpy 3-d array into 2-d array of smaller 3-d arrays
我目前的图像为 numpy 阵列,具有 3 个通道 (RGB)。 我想将其有效地拆分为较小的 3-d 子 arrays 的 2-d 数组。 例如,如果我的图像形状为 (100, 100, 3),我想将其转换为 10 x 10 数组,其中元素是 (10, 10, 3) 图像(子图像),同时保持空间方向。 图像的高度和宽度将始终相等。
我也想扭转整个操作。
如果这很难做到,有没有办法将其转换为行或列顺序的 4-d 数组,而元素仍然相同?
有没有使用 numpy 方法的有效方法?
您可以使用 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 子数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.