如何在m×m矩阵中提取每n×n矩阵

时间:2014-12-13 16:24:44

标签: python arrays

我试图从450×450

的一个矩阵中检索225,30到30个矩阵

使用切片我能够得到一个30乘30的矩阵,但我不知道如何迭代并得到其余的,无论如何要做到这一点?

x = 30
extract = []
extract1 = []

while ( x < 450 ):
    extract1 = test1[x:, x:]
    x += 30
    extract.append(extract1)

2 个答案:

答案 0 :(得分:1)

使用numpy的大步观点:

import numpy as np

def make_windows(x, ws):
    m,n = x.shape
    s,t = ws
    shape = (m/s, n/t) + ws
    strides = (s * x.strides[0], t * x.strides[1]) + x.strides
    windows = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
    return windows.reshape(-1, s, t)

让我们尝试一些数据:

>>> data = np.arange(450*450).reshape(450,450)
>>> windows = make_windows(data, (30,30))
>>> windows.shape
(225, 30, 30)
>>> windows
array([[[     0,      1,      2, ...,     27,     28,     29],
        [   450,    451,    452, ...,    477,    478,    479],
        [   900,    901,    902, ...,    927,    928,    929],
        ..., 
        [ 12150,  12151,  12152, ...,  12177,  12178,  12179],
        [ 12600,  12601,  12602, ...,  12627,  12628,  12629],
        [ 13050,  13051,  13052, ...,  13077,  13078,  13079]],

       [[    30,     31,     32, ...,     57,     58,     59],
        [   480,    481,    482, ...,    507,    508,    509],
        [   930,    931,    932, ...,    957,    958,    959],
        ..., 
        [ 12180,  12181,  12182, ...,  12207,  12208,  12209],
        [ 12630,  12631,  12632, ...,  12657,  12658,  12659],
        [ 13080,  13081,  13082, ...,  13107,  13108,  13109]],

        ...,

答案 1 :(得分:0)

我认为这会为您提供所需的输出,但我确信有更优雅的方式来做到这一点。

import numpy as np

a = np.arange(16).reshape(4,4)
extracts = []
x = 2

for i in xrange(x):
    for j in xrange(x):
        extracts.append(a[i*x :x + i*x, j*x : x + j*x])