使用 image_dataset_from_directory 加载灰度 png 返回 3 通道张量

Wil*_*man 5 python png keras tensorflow tensorflow-datasets

我有一组灰度 png 图像,分为 2 个目录。根据文档,我已使用 image_dataset_from_directory 将它们作为数据集对象加载。当我使用 element_spec 检查已加载的内容时,它说图像有 3 个通道:

from tensorflow.keras.preprocessing import image_dataset_from_directory
Dataset = image_dataset_from_directory('path/to/files')
Dataset.element_spec
Run Code Online (Sandbox Code Playgroud)

返回:

找到属于 2 个类别的 14000 个文件。

(TensorSpec(形状=(无, 256, 256, 3), dtype=tf.float32, 名称=无), TensorSpec(形状=(无,), dtype=tf.int32, 名称=无))

使用 MATLAB 将图像保存为灰度 png,并且我已使用 Linux 命令文件确认它们是灰度的:

$ file path/to/files/class_1/file_1.png
Run Code Online (Sandbox Code Playgroud)

path/to/files/class_1/file_1.png:PNG 图像数据,256 x 256,8 位灰度,逐行扫描

所以现在我要么需要告诉 image_dataset_from_directory 将这些文件加载​​为灰度,要么需要将 3 通道张量 Dataset 对象转换为 1 通道张量。我该怎么办呢?

编辑:

有关使用识别的磁盘上文件的更多信息(来自 ImageMagick):

$ identify -verbose path/to/files/class_1/file_1.png
Run Code Online (Sandbox Code Playgroud)
Image: AI_Optrap/Samples/Set4/relaxed/HL60_normoxia_1_1.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: PseudoClass
  Geometry: 256x256+0+0
  Units: Undefined
  Type: Grayscale
  Base type: Grayscale
  Endianess: Undefined
  Colorspace: Gray
  Depth: 8-bit
  Channel depth:
    gray: 8-bit
  Channel statistics:
    Pixels: 65536
    Gray:
      min: 0 (0)
      max: 255 (1)
      mean: 135.92 (0.533021)
      standard deviation: 36.3709 (0.142631)
      kurtosis: 1.51412
      skewness: 0.035325
      entropy: 0.87207
  Colors: 256
Run Code Online (Sandbox Code Playgroud)

Nic*_*ais 6

默认情况下,image_dataset_from_directory转换为 3 个通道。查看文档

tf.keras.preprocessing.image_dataset_from_directory(
    directory, labels='inferred', label_mode='int', class_names=None,
    color_mode='rgb', batch_size=32, image_size=(256, 256), shuffle=True, seed=None,
    validation_split=None, subset=None, interpolation='bilinear', follow_links=False
)
Run Code Online (Sandbox Code Playgroud)

颜色模式: “灰度”、“rgb”、“rgba”之一。默认值:“rgb”。图像是否将转换为具有 1、3 或 4 通道。

所以只需使用这一行:

Dataset = image_dataset_from_directory('path/to/files', color_mode='grayscale')
Run Code Online (Sandbox Code Playgroud)

现在您的图像将转换为(None, 256, 256, 1).