A manual way to compose a NumPy array out of smaller blocks is to use np.block
or np.bmat
:
h, w, N = 3, 4, 6
A, B, C, D, E, F = [np.full((h,w), i) for i in list('ABCDEF')]
result = np.block([[A, B], [C, D], [E, F]])
yields
array([['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
['C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
['C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
['C', 'C', 'C', 'C', 'D', 'D', 'D', 'D'],
['E', 'E', 'E', 'E', 'F', 'F', 'F', 'F'],
['E', 'E', 'E', 'E', 'F', 'F', 'F', 'F'],
['E', 'E', 'E', 'E', 'F', 'F', 'F', 'F']],
dtype='<U1')
Assuming the blocks are 2D arrays, a more automated way to reshape a NumPy array of blocks is to use unblockshaped
:
import numpy as np
def unblockshaped(arr, h, w):
"""
http://stackoverflow.com/a/16873755/190597 (unutbu)
Return an array of shape (h, w) where
h * w = arr.size
If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols),
then the returned array preserves the "physical" layout of the sublocks.
"""
n, nrows, ncols = arr.shape
return (arr.reshape(h // nrows, -1, nrows, ncols)
.swapaxes(1, 2)
.reshape(h, w))
h, w, N = 3, 4, 6
arr = np.array([np.full((h,w), i) for i in list('ABCDEF')])
result = unblockshaped(arr, h*N//2, w*2)
print(result)
which produces the same result.
See this question for an example
of how to arrange a sequence of images into a grid.