Search code examples
pythonimagetensorflowkerastf.data.dataset

Cannot batch tensors with different shapes in component 0


InvalidArgumentError: Cannot batch tensors with different shapes in component 0. First element had shape [224,224,3] and element 25 had shape [224,224,1].

I have already reshaped images as you can seen here.

def process_path(file_path=train_data):
 image_file= tf.io.read_file(image_dir+file_path+'.jpg')
 image_file=tf.image.decode_jpeg(image_file)
 image_file=tf.image.convert_image_dtype(image_file,tf.float32)
 image_file=tf.image.resize(image_file,[224,224])

 return image_file

X_train = train_data.map(process_path)

Then I just merge the labels and image data

train=tf.data.Dataset.zip((X_train,y_train))
train=train.shuffle(buffer_size=64).batch(32).prefetch(1)
base_res_model.fit(train,epochs=10,verbose=2)

Could the problem be in a corrupted image or I'm missing something in the code?


Solution

  • A color image has 3 channels, R, G, B. However, a greyscale image only has one channel. Element 25 of your list is a greyscale image while the indices before are color. A solution to this would be to pass the number of channels into tf.image.decode_jpeg as follows:

    imagefile=tf.image.decode_jpeg(image_file, channels=3)