我有一个来自图像的 300 x 200 的二维数组。我想为每 20 x 20 block 生成一个坐标对列表,直到数组末尾。
从网格生成坐标对很简单,但我一直不知道如何迭代数组中的 20 x 20 block 。我是 numpy 和数组的新手。
w, h = 300, 200
coordinates = [(x, y) for x in xrange(w) for y in xrange(h)]
请您参考如下方法:
如果你想遍历原始数组,你可以这样做:
w,h = 6,4
n = 2 #Height of window
m = 2 #Width of window
k = h / n #Must divide evenly
l = w / m #Must divide evenly
data = np.random.randint(0,90,(h,w))
data
[[45 39 36 25 30 21]
[48 27 46 48 20 87]
[19 20 59 27 41 52]
[52 11 42 30 85 49]]
for h in xrange(k):
for w in xrange(l):
print data[h*n:(h+1)*n,w*m:(w+1)*m]
[[45 39]
[48 27]]
[[36 25]
[46 48]]
[[30 21]
[20 87]]
[[19 20]
[52 11]]
[[59 27]
[42 30]]
[[41 52]
[85 49]]
您可以切换循环顺序,让不同的窗口先出现。
您还可以预先生成所有索引:
inds = np.arange(w*h).reshape(k,n,l,m).swapaxes(1,2).reshape(k,l,n*m)
#The final reshape can be reshape(k*l,n*m) if you do not want a double loop.
for h in xrange(k):
for w in xrange(l):
print np.take(data,inds[h,w])
[45 39 48 27]
[36 25 46 48]
[30 21 20 87]
[19 20 52 11]
[59 27 42 30]
[41 52 85 49]
您还有这个选择:
[np.split(x,k,axis=0) for x in np.split(data,l,axis=1)]
[[array([[45, 39],
[48, 27]]),
array([[19, 20],
[52, 11]])],
[array([[36, 25],
[46, 48]]),
array([[59, 27],
[42, 30]])],
[array([[30, 21],
[20, 87]]),
array([[41, 52],
[85, 49]])]]
注意上面我切换了输出顺序,你可以使用:
[np.split(x,l,axis=1) for x in np.split(data,k,axis=0)]
为了与所有其他人一样返回相同的结果,我只是想举个例子。
