如何从2d数组构造2d数组

时间:2017-04-02 09:16:28

标签: python arrays numpy

我需要从许多较小的数组中重建特定形状的二维数组(来自图像颜色通道):

import numpy as np
from PIL import Image

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
return (arr.reshape(h//nrows, nrows, -1, ncols)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols))

pic = Image.open('testimage.bmp') # open image
(r, g, b) = pic.split()# split to channels

c = np.asarray(b) # channel b as array

ar = np.empty((0,256),int) # empty array for appending 

n_a = blockshaped(c,8,8) # dividing array into 4 subarrays
n_a2 = np.concatenate(n_a, axis = 0) #concatenate arrays

for i in n_a2: 
    ar = np.append(ar, i) # append array elements

ar = ar.reshape((16,16)) # reshaping

此代码产生以下结果:

enter image description here

它与原始数组不同: enter image description here

这是可以理解的,因为np.concatenate不按我需要的顺序连接数组。问题是如何合并数组以将它们恢复到原始状态?

blockshaped函数来自here

1 个答案:

答案 0 :(得分:1)

重塑以将第一个轴分成三个长度为2,2,8的轴,保持第二个轴不变。然后,使用rollaxis / swapaxes / transpose置换轴并使最终重塑为16 x 16形状 -

n_a2.reshape(2,2,8,8).swapaxes(1,2).reshape(16,16)

运行样本以进行验证 -

In [46]: c = np.random.randint(11,99,(16,16))

In [47]: n_a = blockshaped(c,8,8) # dividing array into 4 subarrays
    ...: n_a2 = np.concatenate(n_a, axis = 0) #concatenate arrays
    ...: 

In [48]: out = n_a2.reshape(2,2,8,8).swapaxes(1,2).reshape(16,16)

In [49]: np.allclose(out, c)
Out[49]: True
相关问题