Is there an efficient way to combine 4 small arrays into one big array using an interleaved 'mosaic' pattern?

Viewed 254

I have 4 square arrays of the same shape

array1 = 1*np.ones((10,10))
array2 = 2*np.ones((10,10))
array3 = 3*np.ones((10,10))
array4 = 4*np.ones((10,10))

I want to recombine them into one big array in an interleaved mosaic pattern as such:

result = np.asarray([[1,2,1,2,...,1,2],\
                     [3,4,3,4,...,3,4],\
                     [1,2,1,2,...,1,2],\
                     ...
                     [3,4,3,4,...,3,4]])

Where result is twice as big in both dimensions as the original individual images.

Is there an efficient way to do this?

To illustrate my question, I used arrays containing constant values but in reality, these 4 arrays would be different images.

1 Answers

Two common approaches for interlacing data in numpy are:

A) Assign each source to a slice of a blank result array, corresponding to where the data should go:

result = np.zeros((20, 20)) # allocate space
result[::2, ::2] = array1 # put those values in the appropriate spots
result[::2, 1::2] = array2
result[1::2, ::2] = array3
result[1::2, 1::2] = array4

B) use stacking to stick the data together in a single array, and then reshape to flatten the data in a way that leaves it interlaced. This typically requires a bit of trial and error, but after playing around with the REPL a bit I came up with:

result = np.hstack((np.dstack((array1, array2)), np.dstack((array3, array4)))).reshape(20, 20)
Related