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

相关文章

HTML5表格语法格式详解

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

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

python dict转换成json格式的实现

《pythondict转换成json格式的实现》本文主要介绍了pythondict转换成json格式的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下... 一开始你变成字典格式data = [ { 'a' : 1, 'b' : 2, 'c编程' : 3,

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 代码解