Skip to content Skip to sidebar Skip to footer

How To Random_crop An Unlabeled Tensorflow Dataset? Valueerror: Dimensions Must Be Equal, But Are 4 And 3

I am trying to augment (random crop) images while loading them using a tensorflow Dataset. I am getting this error when I call the method tf.image.random_crop in the mapped functio

Solution 1:

Try using a batch size of 1:

tensor = tf.image.random_crop(value=tensor, size=(1,256, 256, 3))

But I don't think you should mix high-level data loaders with a lower level tf.data.Dataset. Try using only the latter.

import tensorflow as tf

image_dir = r'C:\Users\user\Pictures'

files = tf.data.Dataset.list_files(image_dir + '\\*jpg')

defload(filepath):
    image = tf.io.read_file(filepath)
    image = tf.image.decode_image(image)
    return image

ds = files.map(load)

defaugment(tensor):
    tensor = tf.cast(x=tensor, dtype=tf.float32)
    tensor = tf.divide(x=tensor, y=tf.constant(255.))
    tensor = tf.image.random_crop(value=tensor, size=(100, 100, 3))
    random_target = tf.random.uniform((1,), dtype=tf.int32, maxval=2)
    return tensor, random_target

train_set_raw = ds.map(augment).batch(32)

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(8, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(loss='binary_crossentropy', optimizer='adam')

history = model.fit(train_set_raw)

Post a Comment for "How To Random_crop An Unlabeled Tensorflow Dataset? Valueerror: Dimensions Must Be Equal, But Are 4 And 3"