0

I have a numpy array of size image_stack 64x28x28x3 which correspond to 64 images of size 28x28x3. What I want is to construct an image of size 224x224x3 which will contain all my images that are in the initial array. How can I do so in numpy? So far I have the code for stacking the images in the same line, however I want 8 lines of 8 columns instead. My code so far:

def tile_images(image_stack):
    """Given a stacked tensor of images, reshapes them into a horizontal tiling for display.""" 
    assert len(image_stack.shape) == 4
    image_list = [image_stack[i, :, :, :] for i in range(image_stack.shape[0])]
    tiled_images = np.concatenate(image_list, axis=1)
    return tiled_images

1 Answer 1

1

Does the following reshape, transpose, reshape trick work?

x.shape # (64, 28, 28, 3)
mosaic = x.reshape(8, 8, 28, 28, 3).transpose((0, 2, 1, 3, 4)).reshape(224, 224, 3)

The first reshape breaks your 64 into lines and columns. Transpose rearranges their order so that we can collapse them in a meaningful way.

Your function would then look like:

def tile_images(x):
    dims = x.shape
    assert len(dims) == 4
    stack_dim = int(np.sqrt(dims[0]))
    res = x.reshape(stack_dim, stack_dim, *dims[1:]).transpose((0, 2, 1, 3, 4))
    tile_size = res.shape[0] * res.shape[1]
    return res.reshape(tile_size, tile_size, -1)
Sign up to request clarification or add additional context in comments.

2 Comments

So the mosaic needs to be the input of my function or to be inside my function too, right?
No, the first example considers x to be your 4D image_stack, and assumes that you only have to do this once, so I hardcoded the numbers when computing mosaic. The second example will take as input the image_stack directly, as a 4D array, and return a 3D array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.