通过更大的矩阵迭代子矩阵 [英] Iterate in submatrices through a bigger matrix

查看:88
本文介绍了通过更大的矩阵迭代子矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,使用for循环可以迭代更大的矩阵,在该矩阵中,每次迭代将输出大小(行,列,深度)(6、3、3)的子矩阵.

I looking for a way in which I using a for loop can iterate through a bigger matrix, in which each iteration will output a sub matrix of size (row, col, depth) (6,3,3).

我的大矩阵存储为numpy矩阵,并且也可能希望每次迭代都这样输出.

My big matrix is stored as numpy matrix, and would possible also like the each iteration to be outputted as such.

>>> import numpy as np
>>> a = np.random.rand(6*3,3*3,3)
>>> print a.shape
(18, 9, 3)
>>> print a
>>> b

变量b应该包含矩阵a的所有大小为(6,3,3)的子矩阵. 每个子矩阵都不应与之前的子矩阵重叠.

The variable b should contain all the sub matrixes of size (6,3,3) from matrix a. Each submatrix should not overlap with the prior.

推荐答案

方法1

我假设我们正在寻找non-overlapping/distinct块.因此,我们可以使用 Scikit-image's view_as_blocks 实用程序-

I am assuming we are looking for non-overlapping/distinct blocks. As such we could use Scikit-image's view_as_blocks utility -

from skimage.util.shape import view_as_blocks

BSZ = (6,3,3)
out = view_as_blocks(a,BSZ).reshape((-1,)+ (BSZ))

样品运行-

In [279]: a = np.random.rand(6*3,3*3,3)

In [280]: out = view_as_blocks(a,BSZ).reshape((-1,)+ (BSZ))

In [281]: out.shape
Out[281]: (9, 6, 3, 3)


方法2

仅使用本机NumPy工具(如reshapingtranspose),这是一种方法-

Using just native NumPy tools like reshaping and transpose, here's one way -

m,n,r = a.shape
split_shp = m//BSZ[0], BSZ[0], n//BSZ[1], BSZ[1], r//BSZ[2], BSZ[2]
out = a.reshape(split_shp).transpose(0,2,4,1,3,5).reshape((-1,)+ (BSZ))

这篇关于通过更大的矩阵迭代子矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆