这可以更快地完成,通过重新塑形和交换轴,然后对所有内核元素进行重复,像这样:
(可以通过重新塑造和交换轴来加速此过程,并在所有内核元素上重复此操作,如下所示:
)
im = np.arange(81).reshape(9,9)
print np.swapaxes(im.reshape(3,3,3,-1),1,2)
这将为您提供一个3*3瓷砖数组,可以在表面上平铺:
[[[[ 0 1 2] [[ 3 4 5] [[ 6 7 8]
[ 9 10 11] [12 13 14] [15 16 17]
[18 19 20]] [21 22 23]] [24 25 26]]]
[[[27 28 29] [[30 31 32] [[33 34 35]
[36 37 38] [39 40 41] [42 43 44]
[45 46 47]] [48 49 50]] [51 52 53]]]
[[[54 55 56] [[57 58 59] [[60 61 62]
[63 64 65] [66 67 68] [69 70 71]
[72 73 74]] [75 76 77]] [78 79 80]]]]
为了获得重叠的瓦片,我们需要重复这个过程8次,但是通过使用
vstack
和
column_stack
的组合来“包装”数组。请注意,右侧和底部的瓦片数组会环绕(这可能是您想要的,具体取决于如何处理边缘条件)。
im = np.vstack((im[1:],im[0]))
im = np.column_stack((im[:,1:],im[:,0]))
print np.swapaxes(im.reshape(3,3,3,-1),1,2)
#Output:
[[[[10 11 12] [[13 14 15] [[16 17 9]
[19 20 21] [22 23 24] [25 26 18]
[28 29 30]] [31 32 33]] [34 35 27]]]
[[[37 38 39] [[40 41 42] [[43 44 36]
[46 47 48] [49 50 51] [52 53 45]
[55 56 57]] [58 59 60]] [61 62 54]]]
[[[64 65 66] [[67 68 69] [[70 71 63]
[73 74 75] [76 77 78] [79 80 72]
[ 1 2 3]] [ 4 5 6]] [ 7 8 0]]]]
用这种方法,您最终得到9组数组,因此您需要将它们重新压缩在一起。对于所有维度可被3整除的数组,这个过程和所有的重塑过程都是通用的:
def new(im):
rows,cols = im.shape
final = np.zeros((rows, cols, 3, 3))
for x in (0,1,2):
for y in (0,1,2):
im1 = np.vstack((im[x:],im[:x]))
im1 = np.column_stack((im1[:,y:],im1[:,:y]))
final[x::3,y::3] = np.swapaxes(im1.reshape(rows/3,3,cols/3,-1),1,2)
return final
比较这个
new
函数与循环遍历所有切片(如下所示),使用
timeit
,对于一个300*300的数组来说,它大约快了4倍。
def old(im):
rows,cols = im.shape
s = []
for x in xrange(1,rows):
for y in xrange(1,cols):
s.append(im[x-1:x+2,y-1:y+2])
return s
mask5
,这样我们可以更好地帮助你,加油! - fraxelcopy_img[x:x+3,y:y+3]
。 - fraxel