tensorflow读取数据-tfrecord格式(II)

2024-08-31 11:18

本文主要是介绍tensorflow读取数据-tfrecord格式(II),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

                       tensorflow读取数据-tfrecord格式(II)

上一篇博文介绍了tensorflow中的tfrecords方法,接下来以保存和读取图片数据为例,详细展示python实现代码

1、single picture

# -*- coding: utf-8 -*-
"""
Spyder Editor"""############single picture
import os
import tensorflow as tf
import cv2
from matplotlib import pyplot as plt
import numpy as npdef write_tfrecords(input,output):''' 借助于 TFRecordWriter 才能将信息写进 TFRecord 文件'''writer = tf.python_io.TFRecordWriter(output)# 读取图片并进行解码image = tf.read_file(input)image = tf.image.decode_jpeg(image)with tf.Session() as sess:image = sess.run(image)shape = image.shape# 将图片转换成 string。image_data = image.tostring()print(type(image))print(len(image_data))name = bytes("example", encoding='utf8')print(type(name))# 创建 Example 对象,并且将 Feature 一一对应填充进去。example = tf.train.Example(features=tf.train.Features(feature={'name': tf.train.Feature(bytes_list=tf.train.BytesList(value=[name])),'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=[shape[0], shape[1], shape[2]])),'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_data]))}))# 将 example 序列化成 string 类型,然后写入。writer.write(example.SerializeToString())writer.close()write_tfrecords('/Users/mac/MyProjects/SR/datasets/lr_img/lr_062.png','example.tfrecord')def _parse_record(example_proto):features = {'name': tf.FixedLenFeature((), tf.string),'shape': tf.FixedLenFeature([3], tf.int64),'data': tf.FixedLenFeature((), tf.string)}parsed_features = tf.parse_single_example(example_proto, features=features)return parsed_featuresdef read_tfrecords(input_file):# 用 dataset 读取 tfrecord 文件dataset = tf.data.TFRecordDataset(input_file)dataset = dataset.map(_parse_record)iterator = dataset.make_one_shot_iterator()with tf.Session() as sess:features = sess.run(iterator.get_next())name = features['name']name = name.decode()img_data = features['data']shape = features['shape']print('=======')print(type(shape))print(len(img_data))# 从 bytes 数组中加载图片原始数据,并重新 reshape.它的结果是 ndarray 数组img_data = np.fromstring(img_data,dtype=np.uint8)image_data = np.reshape(img_data,shape)plt.figure()#显示图片plt.imshow(image_data)plt.show()#将数据重新编码成 jpg 图片并保存img = tf.image.encode_jpeg(image_data)tf.gfile.GFile('example_encode.jpg','wb').write(img.eval())read_tfrecords('example.tfrecord')

2、multi pictures

# -*- coding: utf-8 -*-
"""
Spyder EditorThis is a tfrecords script file.
"""##############multi pictures
import os
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as npdef write_tfrecords(input_path,output):''' 借助于 TFRecordWriter 才能将信息写进 TFRecord 文件'''writer = tf.python_io.TFRecordWriter(output)path = input_pathfile_names = [f for f in os.listdir(path) if f.endswith('.png')] #获取待存文件路径# 读取图片并进行解码for file_name in file_names:file_name = path + file_nameimage = tf.read_file(file_name)image = tf.image.decode_jpeg(image)with tf.Session() as sess:image = sess.run(image)shape = image.shape# 将图片转换成 string。image_data = image.tostring()#print(type(image))#print(len(image_data))name = bytes("train", encoding='utf8')#print(type(name))# 创建 Example 对象,并且将 Feature 一一对应填充进去。example = tf.train.Example(features=tf.train.Features(feature={'name': tf.train.Feature(bytes_list=tf.train.BytesList(value=[name])),'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=[shape[0], shape[1], shape[2]])),'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_data]))}))# 将 example 序列化成 string 类型,然后写入。writer.write(example.SerializeToString())writer.close()def _parse_record(example_proto):features = {'name': tf.FixedLenFeature((), tf.string),'shape': tf.FixedLenFeature([3], tf.int64),'data': tf.FixedLenFeature((), tf.string)}parsed_features = tf.parse_single_example(example_proto, features=features)return parsed_featuresdef read_tfrecords(num,input_file):# 用 dataset 读取 tfrecord 文件dataset = tf.data.TFRecordDataset(input_file)dataset = dataset.map(_parse_record)iterator = dataset.make_one_shot_iterator()with tf.Session() as sess:for i in range(num):features = sess.run(iterator.get_next())name = features['name']name = name.decode()img_data = features['data']shape = features['shape']print('=======')#print(type(shape))#print(len(img_data))# 从 bytes 数组中加载图片原始数据,并重新 reshape.它的结果是 ndarray 数组img_data = np.fromstring(img_data,dtype=np.uint8)image_data = np.reshape(img_data,shape)#显示图片#plt.figure()#plt.imshow(image_data)#plt.show()#将数据重新编码成 jpg 图片并保存img = tf.image.encode_jpeg(image_data)tf.gfile.GFile('train_encode'+str(i)+'.jpg','wb').write(img.eval())if __name__ == '__main__':input_path = '/Users/MyProjects/SR/datasets/lr_img/'output = 'train.tfrecords'write_tfrecords(input_path, output)print ('Write tfrecords: %s done' %output)file_names = [f for f in os.listdir(input_path) if f.endswith('.png')]num = len(file_names)read_tfrecords(num,'train.tfrecords')

 

这篇关于tensorflow读取数据-tfrecord格式(II)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1123748

相关文章

C#中DateTime的格式符的实现示例

《C#中DateTime的格式符的实现示例》本文介绍了C#中DateTime格式符的使用方法,分为预定义格式和自定义格式两类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录DateTime的格式符1.核心概念2.预定义格式(快捷方案,直接复用)3.自定义格式(灵活可控

使用C#导出Excel数据并保存多种格式的完整示例

《使用C#导出Excel数据并保存多种格式的完整示例》在现代企业信息化管理中,Excel已经成为最常用的数据存储和分析工具,从员工信息表、销售数据报表到财务分析表,几乎所有部门都离不开Excel,本文... 目录引言1. 安装 Spire.XLS2. 创建工作簿和填充数据3. 保存为不同格式4. 效果展示5

使用python生成固定格式序号的方法详解

《使用python生成固定格式序号的方法详解》这篇文章主要为大家详细介绍了如何使用python生成固定格式序号,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下... 目录生成结果验证完整生成代码扩展说明1. 保存到文本文件2. 转换为jsON格式3. 处理特殊序号格式(如带圈数字)4

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

Mysql常见的SQL语句格式及实用技巧

《Mysql常见的SQL语句格式及实用技巧》本文系统梳理MySQL常见SQL语句格式,涵盖数据库与表的创建、删除、修改、查询操作,以及记录增删改查和多表关联等高级查询,同时提供索引优化、事务处理、临时... 目录一、常用语法汇总二、示例1.数据库操作2.表操作3.记录操作 4.高级查询三、实用技巧一、常用语

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到

利用Python脚本实现批量将图片转换为WebP格式

《利用Python脚本实现批量将图片转换为WebP格式》Python语言的简洁语法和库支持使其成为图像处理的理想选择,本文将介绍如何利用Python实现批量将图片转换为WebP格式的脚本,WebP作为... 目录简介1. python在图像处理中的应用2. WebP格式的原理和优势2.1 WebP格式与传统

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.