将PNG文件加载到TensorFlow中

4
我正在尝试加载我生成的自定义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文件。

2个回答

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)

0

我认为问题出在 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 格式但失败了。

我该如何使用这个语法加载png文件?尝试通过迭代数据集并使用tf.train.Example.FromString来加载它会导致以下错误:tensorflow.python.framework.errors_impl.DataLossError: corrupted record at 0 - Mehdi Zare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接