python - 将 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 文件。
解决方案
我建议使用 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)
推荐阅读
- image - 为什么 PFM 具有相反的行顺序
- phpmyadmin - 如何在 PMA 搜索窗口中显示普通输入字段而不是下拉框
- reactjs - Next.js 身份验证:身份验证出现 404 错误
- laravel - 无法删除 Laravel 中的数据
- javascript - 画布无法加载
- c++ - 如何删除我的 C++ 代码中的分段错误?
- postgresql - Hibernate / Postgres - 更改默认列类型映射
- android - Kotlin中的高阶函数如何使用另一个参数作为函数类型参数的参数
- c - 如何将数据动态存储在C中的链表中?
- reactjs - 父组件的 ReactJS 状态仅更新子组件而不更新父组件