Search code examples
tensorflowdeep-learningimage-segmentationtf.keras

How to increase dimension of tensors in tensorflow?


I need to increase the dimension of a tensor from 3D to 4D because the tf.image.extract_patches takes input images which is a 4-D Tensor with shape [batch, in_rows, in_cols, depth], where I think depth is for rgb images but what I'm using is greyscale images which produce 3D tensors and in turn throws error in the extract_patches function. So I want to increase the tensor dimension without any changes to its values.

The function works fine when I tried it with rgb image but when the same image is run in greyscale, it throws error.


Solution

  • There are two ways to increase the dimension of a tensor in tensorflow, without repeating values:

    # a. using tf.expand_dims with axis as the last one
    image_rgb = tf.expand_dims(image_grayscale, axis=-1)
    
    # b. using slicing but with tf.newaxis at the desired position (last dim in this case)
    image_rgb = image_grayscale[..., tf.newaxis]