首页 > 解决方案 > Tensorflow.keras 的 ImageDataGenerator.flow_from_directory 如何缩放图像值?

问题描述

我有一个训练有素的 tensorflow 模型,在制作训练数据库时,我使用了

from tensorflow.keras.preprocessing.image import ImageDataGenerator
ImageDataGenerator.flow_from_directory(organized_dir,
                                       target_size=(image_dim, image_dim),
                                       color_mode="grayscale",
                                       batch_size=20,
                                       shuffle=True,
                                       follow_links=True)

(我只是展示了我选择提供的参数,例如在image_dim别处定义的变量)

当我查看next()函数返回的 DirectoryIterator 对象上使用的批次之一时,图像的像素值似乎从其原始 rgb 值 [0,255] 缩放到灰度 [0,1]。我希望它是灰度的,我的理解是 ML 模型在 0 到 1 之间的数字上表现最好。那太好了!

但是,现在我想在不同的图像上使用该模型。在 中打开它们cv2并转换为灰度不会像 tensorflow 那样缩放像素值,它只是将颜色值保持在 [0,255] 而不是 [0,1] 中:

>>> z = cv2.imread("img.png")
>>> cv2.cvtColor(z, cv2.COLOR_BGR2GRAY)
array([[255, 255, 255, ..., 255, 255, 255],
       [255, 255, 255, ..., 255, 255, 255],
       [255, 255, 255, ..., 255, 255, 255],
       ...,
       [255, 255, 255, ..., 255, 255, 255],
       [255, 255, 255, ..., 255, 255, 255],
       [255, 255, 255, ..., 255, 255, 255]], dtype=uint8)

所以,我要问的是如何使用 tensorflow 的数据集使用的相同转换来使图像使用从 [0,255] 到 [0,1] 的像素值。我在这里发现我可以标准化图像:Normalizing images in OpenCV。但我想使用 tensorflow 使用的确切算法/参数,这样我就可以最大限度地提高我在现实世界中的准确性。谢谢

标签: pythontensorflowopencvkerastf.keras

解决方案


您对 ImageDataGenerator 重新缩放图像像素值是不正确的。根据文档,生成器有一个名为 rescale 的参数。对于此参数,文档说明:

rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied,
 otherwise we multiply the data by the value provided
 (after applying all other transformations).

所以要将值从 0 重新调整为 1,然后使用

rescale=1/255

迁移学习中使用的许多模型要求像素值介于 -1 和 +1 之间。对于这种情况,请使用

rescale=1/127.5-1

您正在阅读的图像可能已经重新调整了像素值。测试您的图像是否经过预缩放使用

import numpy as np
import cv2
path_to_file=        #specify the full path to the file
img=cv2.imread(path_to_file,0)# read in image as grayscale
max_pixel_value=np.max(img) #  find maximum pixel value
min_pixel_value=np.min(img) # find minimum pixel value
print('max pixel value= ', max_pixel_value, '  min pixel value= ', min_pixel_value)

推荐阅读