Search code examples
tensorflowkerasdeep-learningtensorflow-datasetspreprocessor

Pixel values change when loading image with TensorFlow Keras preprocessing


I use the function tf.keras.preprocessing.image_dataset_from_directory() and when I check the content of the loaded image, I see that it contains random pixel values, inconsistent with the original image.

Here is how I call the funtion:

ds = tf.keras.preprocessing.image_dataset_from_directory(
    images_path,
    label_mode=None,
    shuffle=False,
    seed=None,
    image_size=(input_height, input_width),
    batch_size=batch_size
)

I then sample the first element of the dataset as follow:

it = iter(ds)
img = next(it).numpy()

The resulting image contains values like 164.3462, which does not make sense because the original image file has only integers as pixel values. If there is a conversion to float32, I would expect all the pixels to have .0 as decimal part of their value.

Am I missing something? I would just like to load my images with the original values, or with the original values followed by .0 in case float32 is needed.

What's wrong?


Solution

  • To use the original values, use 'nearest' as interpolation to resize the image.

    ds = tf.keras.preprocessing.image_dataset_from_directory(
        images_path,
        label_mode=None,
        shuffle=False,
        seed=None,
        interpolation='nearest',
        image_size=(input_height, input_width),
        batch_size=batch_size
    )