[英]How to extract every n by n matrix in an m by m matrix
我正在尝试从一个450 x 450的矩阵中检索225、30 x 30矩阵
使用切片,我可以得到一个30 x 30的矩阵,但是我不确定如何遍历并得到其余的矩阵,无论如何要这样做?
x = 30
extract = []
extract1 = []
while ( x < 450 ):
extract1 = test1[x:, x:]
x += 30
extract.append(extract1)
使用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]],
...,
我认为这可以为您提供所需的输出,尽管我敢肯定还有一种更优雅的方法。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.