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

相关文章

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(.

Java中JSON格式反序列化为Map且保证存取顺序一致的问题

《Java中JSON格式反序列化为Map且保证存取顺序一致的问题》:本文主要介绍Java中JSON格式反序列化为Map且保证存取顺序一致的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未... 目录背景问题解决方法总结背景做项目涉及两个微服务之间传数据时,需要提供方将Map类型的数据序列化为co

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

Ubuntu上手动安装Go环境并解决“可执行文件格式错误”问题

《Ubuntu上手动安装Go环境并解决“可执行文件格式错误”问题》:本文主要介绍Ubuntu上手动安装Go环境并解决“可执行文件格式错误”问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未... 目录一、前言二、系统架构检测三、卸载旧版 Go四、下载并安装正确版本五、配置环境变量六、验证安装七、常见

使用Python开发Markdown兼容公式格式转换工具

《使用Python开发Markdown兼容公式格式转换工具》在技术写作中我们经常遇到公式格式问题,例如MathML无法显示,LaTeX格式错乱等,所以本文我们将使用Python开发Markdown兼容... 目录一、工具背景二、环境配置(Windows 10/11)1. 创建conda环境2. 获取XSLT

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab