使用 TensorFlow Keras 预处理加载图像时像素值发生变化

Pixel values change when loading image with TensorFlow Keras preprocessing

我使用 tf.keras.preprocessing.image_dataset_from_directory() 函数,当我检查加载图像的内容时,我发现它包含随机像素值,与原始图像不一致。

我是这样调用函数的:

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
)

然后我对数据集的第一个元素进行如下采样:

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

生成的图像包含像 164.3462 这样的值,这没有意义,因为原始图像文件只有整数作为像素值。如果转换为 float32,我希望所有像素都将 .0 作为其值的小数部分。

我错过了什么吗?我只想使用原始值加载我的图像,或者使用原始值后跟 .0 以防需要 float32。

怎么了?

这是因为 image_dataset_from_directory 在尝试将图像调整为 (input_height, input_width) 时使用默认的“bilinear”插值。检查 this link 以获得插值方法的其他选项。

要使用原始值,请使用 'nearest' 作为插值来调整图像大小。

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
)