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

相关文章

Python中Windows和macOS文件路径格式不一致的解决方法

《Python中Windows和macOS文件路径格式不一致的解决方法》在Python中,Windows和macOS的文件路径字符串格式不一致主要体现在路径分隔符上,这种差异可能导致跨平台代码在处理文... 目录方法 1:使用 os.path 模块方法 2:使用 pathlib 模块(推荐)方法 3:统一使

Java中使用注解校验手机号格式的详细指南

《Java中使用注解校验手机号格式的详细指南》在现代的Web应用开发中,数据校验是一个非常重要的环节,本文将详细介绍如何在Java中使用注解对手机号格式进行校验,感兴趣的小伙伴可以了解下... 目录1. 引言2. 数据校验的重要性3. Java中的数据校验框架4. 使用注解校验手机号格式4.1 @NotBl

Python批量调整Word文档中的字体、段落间距及格式

《Python批量调整Word文档中的字体、段落间距及格式》这篇文章主要为大家详细介绍了如何使用Python的docx库来批量处理Word文档,包括设置首行缩进、字体、字号、行间距、段落对齐方式等,需... 目录关键代码一级标题设置  正文设置完整代码运行结果最近关于批处理格式的问题我查了很多资料,但是都没

基于Python开发PDF转Doc格式小程序

《基于Python开发PDF转Doc格式小程序》这篇文章主要为大家详细介绍了如何基于Python开发PDF转Doc格式小程序,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用python实现PDF转Doc格式小程序以下是一个使用Python实现PDF转DOC格式的GUI程序,采用T

Python如何实现读取csv文件时忽略文件的编码格式

《Python如何实现读取csv文件时忽略文件的编码格式》我们再日常读取csv文件的时候经常会发现csv文件的格式有多种,所以这篇文章为大家介绍了Python如何实现读取csv文件时忽略文件的编码格式... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍我们再日常读取csv文件的时候经常

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解

IDEA如何将String类型转json格式

《IDEA如何将String类型转json格式》在Java中,字符串字面量中的转义字符会被自动转换,但通过网络获取的字符串可能不会自动转换,为了解决IDEA无法识别JSON字符串的问题,可以在本地对字... 目录问题描述问题原因解决方案总结问题描述最近做项目需要使用Ai生成json,可生成String类型

AI基础 L9 Local Search II 局部搜索

Local Beam search 对于当前的所有k个状态,生成它们的所有可能后继状态。 检查生成的后继状态中是否有任何状态是解决方案。 如果所有后继状态都不是解决方案,则从所有后继状态中选择k个最佳状态。 当达到预设的迭代次数或满足某个终止条件时,算法停止。 — Choose k successors randomly, biased towards good ones — Close

从0到1,AI我来了- (7)AI应用-ComfyUI-II(进阶)

上篇comfyUI 入门 ,了解了TA是个啥,这篇,我们通过ComfyUI 及其相关Lora 模型,生成一些更惊艳的图片。这篇主要了解这些内容:         1、哪里获取模型?         2、实践如何画一个美女?         3、附录:               1)相关SD(稳定扩散模型的组成部分)               2)模型放置目录(重要)

easyui同时验证账户格式和ajax是否存在

accountName: {validator: function (value, param) {if (!/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/i.test(value)) {$.fn.validatebox.defaults.rules.accountName.message = '账户名称不合法(字母开头,允许4-16字节,允许字母数字下划线)';return fal