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
此代码将产生以下结果:
哪个underst因为np.concatenate不按照我需要的顺序连接数组。问题是如何合并数组以将它们恢复到原始状态?
blockshaped功能是从here