votes up 8

'image' (shape %s) must have either 3 or 4 dimensions.

Package:
Exception Class:
ValueError

Raise code

is_batch = False
      image = array_ops.expand_dims(image, 0)
    elif image_shape.ndims is None:
      is_batch = False
      image = array_ops.expand_dims(image, 0)
      image.set_shape([None] * 4)
    elif image_shape.ndims != 4:
      raise ValueError(
          '\'image\' (shape %s) must have either 3 or 4 dimensions.' %
          image_shape)

    assert_ops = _CheckAtLeast3DImage(image, require_static=False)
    batch, height, width, depth = _ImageDimensions(image, rank=4)

    after_padding_width = target_width - offset_width - width

    a
😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 2 votes down

The function pad_to_bounding_box pads an image with zeros to the specified height and width.

The image parameter should be 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels]

Usage:

output = tf.image.pad_to_bounding_box(image, 
                                      offset_height, 
                                      offset_width, 
                                      target_height, 
                                      target_width)

Reproducing the error:

import tensorflow as tf


image = tf.random.normal((28,28))
padded_image = tf.image.pad_to_bounding_box(image, 433231)
print(padded_image.shape)

The error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-4474a7b62f1c> in <module>()
      2 
      3 image = tf.random.normal((28,28))
----> 4 padded_image = tf.image.pad_to_bounding_box(image, 4, 3, 32, 31)
      5 print(padded_image.shape)

/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs)
    204     """Call target, and fall back on dispatchers if there is a TypeError."""
    205     try:
--> 206       return target(*args, **kwargs)
    207     except (TypeError, ValueError):
    208       # Note: convert_to_eager_tensor currently raises a ValueError, not a

/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py in pad_to_bounding_box(image, offset_height, offset_width, target_height, target_width)
   1063       raise ValueError(
   1064           '\'image\' (shape %s) must have either 3 or 4 dimensions.' %
-> 1065           image_shape)
   1066 
   1067     assert_ops = _CheckAtLeast3DImage(image, require_static=False)

ValueError: 'image' (shape (28, 28)) must have either 3 or 4 dimensions.


Fixed version of the code:

import tensorflow as tf


image = tf.random.normal((28,28,3))
padded_image = tf.image.pad_to_bounding_box(image, 433231)
print(padded_image.shape)

Output:

(32, 31, 3)

Jul 10, 2021 kellemnegasi answer
kellemnegasi 22.6k

Add a possible fix

Please authorize to post fix