Concatenate two images in the channel dimension?

I have to concatenate two images in the channel dimension in either MATLAB or Python.

Let's say we take two gray-scale input images, where each has for example the dimension [1, 1, 28, 28] (i.e. 1 image, 1 channel, 28x28 resolution). How can we concatenate them to be one image of size [1, 2, 28, 28]?

3 answers

  • answered 2018-11-08 08:24 user7431005

    I'm not sure what you want to do with your fist dimension but this works for your example:

    img1 = randi(255,1,1,28,28); % first image
    img2 = randi(255,1,1,28,28); % second image
    img1(1,end+1,:,:) = img2; % stack second image on top of first image
    size(img1) % [ 1 2 28 28]

  • answered 2018-11-08 08:52 Dev-iL

    In MATLAB you would usually use the cat command for this:

    bigMat = cat(dimNo, matA, matB); % dimNo can be 1, 2, ...

    But in the case of concatenating along the 2nd dimension, you can also simply use [... ; ...]:

    bigMat = [matA; matB];

    (which is equivalent to the vertcat function).

    If you know in advance how many matrices you'd like to concatenate (i.e. the final size of the result), you should preallocate your matrix using e.g. bigMat = zeros(1, N, 28, 28), then put each image in its correct position similarly to the previous answer -

    img1(:,n,:,:) = img2; % where n is 1..N, and not anything like end+1

    We don't want to use end+1 as this incurs performance losses related to constant reallocation of larger and larger arrays and copying all contents of the array each time.

  • answered 2018-11-08 09:14 randomwalker

    Python: Use numpy for this operation:

    import numpy as np
    img1, img2 = np.random.rand(1,1,28,28), np.random.rand(1,1,28,28)
    img = np.concatenate([img1, img2], axis=1)

    The argument axis=1 defines the axis along which the operation is executed.