将 PNG 文件加载到 TensorFlow 中

Loading PNG files into TensorFlow

我正在尝试加载我生成的自定义 png 文件来训练我的模型。按照 TensorFlow 指南 here 的说明,我使用了以下代码:

import tensorflow as tf
import numpy as np
from pathlib import Path, WindowPath

train_df = pd.DataFrame(
    {'file_name': {0: WindowsPath('hypothesis/temp/81882f4e-0a94-4446-b4ac-7869cf198534.png'), 1: WindowsPath('hypothesis/temp/531162e2-2b4c-4e64-8b3f-1f285b0e1040.png')}, 'label': {0: -0.019687398020669655, 1: 0.0002379227226001479}}
)

file_path_list = [i.read_bytes() for i in train_df['file_name']]

dataset = tf.data.TFRecordDataset(filenames=file_path_list)

raw_example = next(iter(dataset))
parsed = tf.train.Example.FromString(raw_example.numpy())


运行 raw_example... 行 returns 这个错误信息:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 43: invalid start byte

我使用 matplotlib 生成了 PNG 文件。

我建议使用 tensorflow 的内置 io 方法读取 png 文件。下面的代码片段将生成扩展名为 .png 的文件列表,然后遍历它们。在每次迭代期间,它读取文件然后解码 png 编码图像

image_dir = 'hypothesis/temp'
image_root = pathlib.Path(image_dir)
list_ds = tf.data.Dataset.list_files(str(image_root/'*.png'))
for f in list_ds:
  image = tf.io.read_file(f)
  image = tf.io.decode_png(image)

我认为问题是i.read_bytes()。当您只需要文件名时,它会读取文件的内容。

最小的变化是这样的:

file_path_list = [str(i) for i in train_df['file_name']]
dataset = tf.data.TFRecordDataset(filenames=file_path_list)

但如果您只想要文件路径列表,则没有理由先构建数据框:

file_path_list = ['foo/bar/1.png', 'foo/bar/2.png']

您收到错误的原因是 TFRecordDataset() 需要文件名中的字符串列表,因此它尝试将二进制文件数据转换为 utf-8 但失败了。