将 PNG 文件加载到 TensorFlow 中

Meh*_*are 4 python tensorflow tensorflow-datasets tensorflow2.0

我正在尝试加载我生成的定制 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())


Run Code Online (Sandbox Code Playgroud)

运行该raw_example...行会返回以下错误消息:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 43: invalid start byte
Run Code Online (Sandbox Code Playgroud)

我使用 matplotlib 生成了 PNG 文件。

DMo*_*ony 5

我建议使用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)
Run Code Online (Sandbox Code Playgroud)