tensorflow 读、存取 图像 数据的 TFRecord 方法 (示例)
1. 利用TFRecord 格式 读、存 取 Mnist数据集的方法
存取 Mnist数据集的方法 (TFRecord格式)
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np def _float32_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) mnist=input_data.read_data_sets('./data', dtype=tf.uint8, one_hot=True)
"""
print(mnist.train.images)
print(mnist.train.labels)
print(mnist.test.images)
print(mnist.test.labels)
"""
train_images=mnist.train.images
train_labels=mnist.train.labels
#test_images=mnist.test.images
#test_labels=mnist.test.labels train_num=mnist.train.num_examples
#test_num=mnist.test.num_examples pixels=train_images.shape[1] # 784 = 28*28 file_out='./data/output.tfrecords'
writer=tf.python_io.TFRecordWriter(file_out) for index in range(train_num):
image_raw=train_images[index].tostring() #转换为bytes序列 example=tf.train.Example(features=tf.train.Features(feature={
'pixels': _int64_feature(pixels),
'label':_int64_feature(np.argmax(train_labels[index])),
'x':_float32_feature(0.1),
'image_raw':_bytes_feature(image_raw)})) writer.write(example.SerializeToString())
writer.close()
读取 Mnist数据集的方法 (TFRecord格式)
import tensorflow as tf
reader=tf.TFRecordReader()
files=tf.train.match_filenames_once('./data/output.*')
#filename_queue=tf.train.string_input_producer(['./data/output.tfrecords'])
filename_queue=tf.train.string_input_producer(files)
_, serialized_example=reader.read(filename_queue)
features=tf.parse_single_example(serialized_example,
features={
'image_raw':tf.FixedLenFeature([], tf.string),
'pixels':tf.FixedLenFeature([], tf.int64),
'label':tf.FixedLenFeature([], tf.int64),
'x':tf.FixedLenFeature([], tf.float32)
})
#print(features['image_raw']) # tensor string (bytes tensor string tensor)
# necessary operation
# bytes_list to uint8_list
image=tf.decode_raw(features['image_raw'], tf.uint8)
#print(image) # tensor uint8
label=tf.cast(features['label'], tf.int32)
pixels=tf.cast(features['pixels'], tf.int32)
#image.set_shape([pixels**0.5, pixels**0.5])
image.set_shape([784])
batch_size=128
image_batch, label_batch, pixels_batch=tf.train.batch([image, label, pixels], batch_size=batch_size, capacity=1000+3*batch_size)
coord=tf.train.Coordinator()
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
threads=tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(3):
print(sess.run([image_batch, label_batch, pixels_batch]))
coord.request_stop()
coord.join(threads)
==================================================================
2. 利用TFRecord 格式 存取 文件夹内图片的方法

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np def _float32_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) file_out='./data/output1.tfrecords'
writer=tf.python_io.TFRecordWriter(file_out) files = tf.gfile.Glob('./data/*.jpg')
sess=tf.Session()
for file in files:
image_raw_data = tf.gfile.FastGFile(file,'rb').read() img_data = tf.image.decode_jpeg(image_raw_data) # tensor
img_data = sess.run(img_data) # np.array int
resized = img_data.tostring() # np.array string uint8 example=tf.train.Example(features=tf.train.Features(feature={
'y':_int64_feature(1),
'x':_float32_feature(0.1),
'image_raw':_bytes_feature(resized)})) writer.write(example.SerializeToString())
writer.close()
文件读取过程使用 输入队列 :
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np def _float32_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _int64_feature(value):
#value类型应为:int,long,float
#return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) #value类型应为:[int],[long],[float], 这里为int的list类型
return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) file_out='./data/output2.tfrecords'
writer=tf.python_io.TFRecordWriter(file_out) files = tf.train.match_filenames_once('./data/*.jpg') # string_input_producer会产生一个文件名队列
filename_queue = tf.train.string_input_producer(files, shuffle=False, num_epochs=3)
# reader从文件名队列中读数据。对应的方法是reader.read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue) img_data = tf.image.decode_jpeg(value) # np.array 转换为 tensor
#print(sess.run([key, img_data]))
#print(img_data.get_shape())
img_data.set_shape([None, None, 3]) img_float = tf.image.convert_image_dtype(img_data, tf.float32)
img_float = tf.image.resize_images(img_float, [300, 300], method=0) with tf.Session() as sess:
# tf.train.string_input_producer定义了一个epoch变量,要对它进行初始化
tf.local_variables_initializer().run() x=np.array([[1,1,1,1],[1,1,1,1]]) coord = tf.train.Coordinator() # 使用start_queue_runners之后,才会开始填充队列
threads = tf.train.start_queue_runners(sess=sess, coord=coord) for _ in range(3):
resized=sess.run(img_data)
resized = resized.tostring() example=tf.train.Example(features=tf.train.Features(feature={
'x':_int64_feature(x.reshape(x.size).tolist()),
'x2':_int64_feature([1,1]),
'y':_float32_feature(0.1),
'image_raw':_bytes_feature(resized)})) writer.write(example.SerializeToString())
writer.close() coord.request_stop()
coord.join(threads)
tensorflow 读、存取 图像 数据的 TFRecord 方法 (示例)的更多相关文章
- TensorFlow中读取图像数据的三种方式
本文面对三种常常遇到的情况,总结三种读取数据的方式,分别用于处理单张图片.大量图片,和TFRecorder读取方式.并且还补充了功能相近的tf函数. 1.处理单张图片 我们训练完模型之后,常常要用图片 ...
- Tensorflow 处理libsvm格式数据生成TFRecord (parse libsvm data to TFRecord)
#写libsvm格式 数据 write libsvm #!/usr/bin/env python #coding=gbk # ================================= ...
- Oracle在本地调试成功读取数据,但是把代码放到服务器读不出数据的解决方法。
用MVC EF框架开发项目,数据库用的是Oracle,本地调试的时候一切正常,但是把代码编译之后放到服务器就会读不出数据. 原因:本地调试环境与服务器环境不一致. 办法:在服务器上装ODT.NET组件 ...
- 快速遍历OpenCV Mat图像数据的多种方法和性能分析 | opencv mat for loop
本文首发于个人博客https://kezunlin.me/post/61d55ab4/,欢迎阅读! opencv mat for loop Series Part 1: compile opencv ...
- Delphi存取图像完整解决方案
http://blog.sina.com.cn/s/blog_693cf1cf0100plkq.html 对于涉及图像数据的数据库应用程序,图像数据的存取技术是一个关键.由于缺少技术文档及DEMO例程 ...
- Inter IPP 处理图像数据的方法
Inter IPP没有读取图片和保存图片的函数,需要结合opencv完成这个功能. opencv读到图片以后逐个像素点赋值给IPP显然是不可取的,方法如下: int main(int argc, ch ...
- vc/mfc获取rgb图像数据后动态显示及保存图片的方法
vc/mfc获取rgb图像数据后动态显示及保存图片的方法 该情况可用于视频通信中获取的位图数据回放显示或显示摄像头捕获的本地图像 第一种方法 #include<vfw.h> 加载 vfw3 ...
- [转]MFC子线程更改图像数据后更新主窗口图像显示方法
程序思路是由外部的输入输出控制卡发出采集图像信号,之后相机采集图像得到图像数据指针,接收图像数据指针创建成图像最后显示到MFC对话框应用程序的Picture Control控件上,同时,为了标定相机位 ...
- (转)原始图像数据和PDF中的图像数据
比较原始图像数据和PDF中的图像数据,结果见表1.1.表1.1中各种“解码器”的解释见本文后续的“PDF支持的图像格式”部分,“PDF中的图像数据”各栏中的数据来自开源的PdfView.如果您有兴趣查 ...
- 基于FPGA的Uart接收图像数据至VGA显示
系统框图 前面我们设计了基于FPGA的静态图片显示,接下来我们来做做基于FPGA的动态图片显示,本实验内容为:由PC端上位机软件通过串口发送一幅图像数据至FPGA,FPGA内部将图像数据存储,最后扫描 ...
随机推荐
- 如何防止 Elasticsearch 服务 OOM ?
ES 和传统关系型数据库有很多区别, 比如传统数据中普遍都有一个叫"最大连接数"的设置.目的是使数据库系统工作在可控的负载下,避免出现负载过高,资源耗尽,谁也无法登录的局面. 那 ...
- 关于 "= default" 和 "= delete" 函数
在 C++ 11 中,"= default" 和 "= delete" 函数使我们能够显示指定成员函数是否自动生成. 其中,"= delete&quo ...
- 【原创】EtherCAT主站IgH解析(二)-- Linux/Windows/RTOS等多操作系统IgH EtherCAT主站移植指南
版权声明:本文为本文为博主原创文章,转载请注明出处.如有问题,欢迎指正.博客地址:https://www.cnblogs.com/wsg1100/ 前言 目前,EtherCAT商用主站有:Aconti ...
- python重拾基础第四天
本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 1. 列表生成式,迭代器&生成器 列表生成式 我现在有个需求, ...
- Stable Diffusion(二)WebUI使用指南
1. 前言 基于 https://stable-diffusion-art.com/ 内的教程进行翻译与整理,帮助快速上手 stable-diffusion 的使用. 2. 环境 AWS DeepLe ...
- Python_9 py文件导入和路径处理
一.查缺补漏 Python中两个值交换可以直接交换如:a,b=b,a 冒泡就是从小到大排序,因为越到后越大 自动导包也适用于自己创建的模块 关于正斜杠和反斜杠https://www.cnblogs.c ...
- python3 podman库
前言 最近在使用 podman, 需要调用一些 podman的接口,podman官网提供的接口并不是很详尽,使用 unix.sock 的方式调用有一 些困难.后来测试 ai 工具时,其提供了一个比较好 ...
- debian11安装备忘
1. 网卡驱动 参考网址:如何安装Debian RTL8821CE驱动? 2. 分辨率 貌似还是有点问题,还要进一步研究一下 参考网址:虚拟机中debian11修改控制台(console)分辨率|li ...
- 算法金 | 一个强大的算法模型,GPR !!
大侠幸会,在下全网同名「算法金」 0 基础转 AI 上岸,多个算法赛 Top 「日更万日,让更多人享受智能乐趣」 抱个拳,送个礼 高斯过程回归(GPR)是一种非参数化的贝叶斯方法,用于解决回归问题.与 ...
- Java高效率查询Mysql节点树数据
示例 目前有一个功能:任务计划管理,必然存在多级子任务的父子级关系,每个任务还会存在其它数据的关联表. mysql无法一次性递归查出想要的数据结构,想必很多人都会是通过根目录递归查询数据库的方式查出树 ...