Home > Software engineering >  InvalidArgumentError: Input filename tensor must be scalar, but had shape: [1] [Op:ReadFile]
InvalidArgumentError: Input filename tensor must be scalar, but had shape: [1] [Op:ReadFile]

Time:11-01

I have trained an image classifier. Now I want to feed some images to get some predictions, using the below code.

def fd(t_embeddings, imagesss, k=1, normalize=True):
  imgr = tf.io.read_file(imagesss)
  imgr = tf.expand_dims(imgr, axis=0)
  i_embedding = vision_encoder(tf.image.resize(imgr, (299, 299)))
  if normalize:
    image_embeddings = tf.math.l2_normalize(t_embeddings, axis=1)
    query_embedding = tf.math.l2_normalize(i_embedding, axis=1)
  dot_similarity = tf.matmul(query_embedding, image_embeddings, transpose_b=True)
  results = tf.math.top_k(dot_similarity, k).indices.numpy()
  return [[df['findings'][idx] for idx in indices] for indices in results] 

Code to get input image

im = "/content/1000_IM-0003-1001.dcm.png"
matches = fd(t_embeddings, 
                   [im], 
                   normalize=True)[1]
for i in range(9):
  print((matches[i]))

However I get this error InvalidArgumentError: Input filename tensor must be scalar, but had shape: [1] [Op:ReadFile]. I think my image needs to be converted to scalar form but I don't know how to do it.

CodePudding user response:

The input type for tf.io.read_file has to be a string. It cannot be a list [im]. Try:

import tensorflow as tf

imagesss = '/content/result_image.png'

imgr = tf.io.read_file(imagesss)

If you have multiple images, you can use a loop to go through them all. See the docs for more information.

  • Related