mul_sal
mul_sal

Reputation: 1

How to use tf.pad without batch size axis?

I'm trying to use tf.pad for image of shape (?, M, N), here ? is the batch size (not fixed) and M,N are image height, width, respectively. My tensorflow version is 1.14.

For example, if the input x (with dtype=tf.float32) is from MNIST, then M=N=28 with unknown batch size ? : (?, M, N).

To pad (zero) this image with padding size : (1,1,1,1) so the output size (?, 30,30), I used the following code:

paddings = tf.constant([[1,1], [1,1]])

output = tf.pad(x[1:], paddings, "CONSTANT", constant_values = 0)

But it doesn't work. I think it's because x[1:] is not the each image (M,N). How can i use tf.pad to tensor (?, M, N) with (1,1,1,1) so the size of output image (?,M + 2,N + 2) in tensorflow version 1.14?

Thank you.

Upvotes: 0

Views: 1533

Answers (1)

Mahendra Singh Meena
Mahendra Singh Meena

Reputation: 608

In the tf.pad paddings is an integer tensor with shape [n, 2], where n is the rank of tensor. https://www.tensorflow.org/api_docs/python/tf/pad

So you need to change the padding tensor like following:

img = tf.random.uniform((1,28,28))
print(img.shape)

>>> (1, 28, 28)

paddings = tf.constant([[0, 0,], [1, 1], [1, 1]])
img_padded = tf.pad(img, paddings)

print(img_padded.shape)

>>> (1, 30, 30)

I tested the code on tf 2.x but the same should also work with tf 1.x .

Upvotes: 1

Related Questions