Pixel values change when loading image with TensorFlow Keras preprocessing

624 views Asked by At

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?

2

There are 2 answers

0
Tou You On BEST ANSWER

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
)
1
Bashir Kazimi On

That's because the image_dataset_from_directory uses a default 'bilinear' interpolation when trying to resize the image to (input_height, input_width). Check this link for other options to interpolation methods.