william007
william007

Reputation: 18525

How to make tensor to have four dimension?

The following code:

def decode_img(img):
  # convert the compressed string to a 3D uint8 tensor
  img = tf.image.decode_jpeg(img, channels=3)
  # Use `convert_image_dtype` to convert to floats in the [0,1] range.
  img = tf.image.convert_image_dtype(img, tf.float32)
  # resize the image to the desired size.
  return tf.image.resize(img, [200, 200])


def process_path(file_path):
  #label = get_label(file_path)
  # load the raw data from the file as a string
  img = tf.io.read_file(file_path)
  img = decode_img(img)
  return img

model.predict(process_path('data/train/nonfood/0_808.jpg'))

Give the following error

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (200, 200, 3)

I expect I need to format the image to size

(1,200,200,3)

But what's the right syntax to do the formatting?

Upvotes: 2

Views: 723

Answers (1)

Timbus Calin
Timbus Calin

Reputation: 14983

You need to simulate the batch_size index, since in Keras and TensorFlow you can only make predictions on batches.

You can use np.expand_dims(photo,axis=0) or tf.expand_dims(photo,axis=0)

Translated to your case, this means that in your decode_img, return tf.expand_dims(img,0)

Upvotes: 2

Related Questions