将2d阵列切成较小的2d阵列有没有办法将ndy中的2d数组切成较小的2d数组?例[[1,2,3,4], -> [[1,2] [3,4] [5,6,7,8]] [5,6] [7,8]]所以我基本上想要将2x4阵列减少为2个2x2阵列。寻找用于图像的通用解决方案。
3 回答

红糖糍粑
TA贡献1815条经验 获得超6个赞
你应该能够打破你的数组转换成“块”使用的一些组合reshape
和swapaxes
:
def blockshaped(arr, nrows, ncols): """ Return an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array should look like n subblocks with each subblock preserving the "physical" layout of arr. """ h, w = arr.shape assert h % nrows == 0, "{} rows is not evenly divisble by {}".format(h, nrows) assert w % ncols == 0, "{} cols is not evenly divisble by {}".format(w, ncols) return (arr.reshape(h//nrows, nrows, -1, ncols) .swapaxes(1,2) .reshape(-1, nrows, ncols))
圈 c
c = np.arange(24).reshape((4,6))print(c)# [[ 0 1 2 3 4 5]# [ 6 7 8 9 10 11]# [12 13 14 15 16 17]# [18 19 20 21 22 23]]
成
print(blockshaped(c, 2, 3))# [[[ 0 1 2]# [ 6 7 8]]# [[ 3 4 5]# [ 9 10 11]]# [[12 13 14]# [18 19 20]]# [[15 16 17]# [21 22 23]]]
我已经张贴了反函数,unblockshaped
在这里,和N维泛化这里。这种概括可以更深入地了解该算法背后的推理。
请注意,还有超级鱼类 blockwise_view
。它以不同的格式排列块(使用更多的轴),但它的优点是(1)总是返回视图,(2)能够处理任何维度的数组。

慕标5832272
TA贡献1966条经验 获得超4个赞
在我看来,这是一个任务numpy.split
或一些变体。
例如
a = np.arange(30).reshape([5,6]) #a.shape = (5,6)
a1 = np.split(a,3,axis=1)
#'a1' is a list of 3 arrays of shape (5,2)
a2 = np.split(a, [2,4])
#'a2' is a list of three arrays of shape (2,5), (2,5), (1,5)
如果您有NxN图像,则可以创建例如2个NxN / 2个子图像的列表,然后沿另一个轴划分它们。
numpy.hsplit
并且numpy.vsplit
也可用。
添加回答
举报
0/150
提交
取消