首页 > 解决方案 > 将 PNG 文件加载到 TensorFlow 中

问题描述

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

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...行会返回此错误消息:

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

我使用 matplotlib 生成了 PNG 文件。

标签: pythontensorflowtensorflow2.0tensorflow-datasets

解决方案


我建议使用 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)

推荐阅读