2017-04-02 132 views
1

我需要从许多较小的阵列的重构的具体形状的2D阵列(从图像颜色通道):如何从2D阵列构造的2D阵列

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

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

blockshaped功能是从here

回答

1

重塑于第一轴线分成长度2,2,8的三个轴,保持第二轴线,因为它是。然后,置换与rollaxis/swapaxes/transpose和最终重塑轴具有16 x 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 
- 用于验证

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

样品运行