您可以使用一些轴的重塑和交换-
A.reshape(h//ph,ph,w//pw,pw,-1).swapaxes(1,2)
样本运行-
In [46]: # Sample inputs
...: h,w,c = 10,12,3
...: ph, pw = 2,2
...: A = np.random.randint(0,9,(h,w,c))
...:
In [47]: A.reshape(h//ph,ph,w//pw,pw,-1).swapaxes(1,2).shape
Out[47]: (5, 6, 2, 2, 3)
沿前两个轴的每个元素(作为块)表示面片。因此对于提供的样本,我们将
5 x 6 = 30
补丁。
如果希望这些面片沿着一个合并的第一个轴,请使用一个或多个面片
reshape
-
In [85]: out = A.reshape(h//ph,ph,w//pw,pw,-1).swapaxes(1,2).reshape(-1,ph,pw,c)
In [86]: out.shape
Out[86]: (30, 2, 2, 3)
让我们通过手动检查值本身进行验证-
In [81]: A[:ph,:pw] # First patch
Out[81]:
array([[[6, 5, 2],
[4, 0, 1]],
[[0, 0, 4],
[2, 3, 0]]])
In [82]: A[:ph,pw:2*pw] # Second patch
Out[82]:
array([[[8, 3, 3],
[0, 0, 2]],
[[8, 5, 4],
[3, 4, 6]]])
In [83]: out[0]
Out[83]:
array([[[6, 5, 2],
[4, 0, 1]],
[[0, 0, 4],
[2, 3, 0]]])
In [84]: out[1]
Out[84]:
array([[[8, 3, 3],
[0, 0, 2]],
[[8, 5, 4],
[3, 4, 6]]])