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内部将图像数据存储,最后扫描 ...
随机推荐
- 如何将 iPhone 的照片同步到 windows 电脑上
首先在电脑上,新建一个文件夹,并把共享权限打开. 文件夹 右键 属性,共享,添加 Everyone. 然后,让手机和电脑连接到同一个局域网,手机热点即可. 在手机端看 文件 app,找到电脑的共享文件 ...
- Javascript高级程序设计第五章 | ch5 | 阅读笔记
基本引用类型 Date 在不给定时间的情况下创建Date实例,创建的对象将保存当前的日期和时间. 要基于其他时间创建Date对象,必须传入其毫秒时表示 Date.parse() 月/日/年(5/21/ ...
- 『手写Mybatis』实现映射器的注册和使用
前言 如何面对复杂系统的设计? 我们可以把 Spring.MyBatis.Dubbo 这样的大型框架或者一些公司内部的较核心的项目,都可以称为复杂的系统. 这样的工程也不在是初学编程手里的玩具项目,没 ...
- Diffusers实战
Smiling & Weeping ---- 一生拥有自由和爱,是我全部的野心 1. 环境准备 %pip install diffusers from huggingface_hub impo ...
- 【译】向您介绍改版的 Visual Studio 资源管理器
随着最近 Visual Studio 的资源管理器的改进,开发人员将得到一种全新的享受!我们非常激动地宣布重新设计的 Visual Studio 资源管理器,相信我们,它将改变游戏规则. 在 Visu ...
- 使用Scrcpy 在电脑显示手机画面并控制安卓设备
使用Scrcpy 显示手机画面并控制手机 原文(有删改):https://www.iplaysoft.com/scrcpy.html 背景 本文适用于安卓开发人员,不针对普通安卓手机用户. 在安卓开发 ...
- MyBatis插件:通用mapper(tk.mapper)
简单认识通用mapper 了解mapper 作用:就是为了帮助我们自动的生成sql语句 通用mapper是MyBatis的一个插件,是pageHelper的同一个作者进行开发的 作者gitee地址:h ...
- P9210 题解
学长给我们讲了就顺便来写一篇题解. 首先最优解一定包括根,不然一定可以从当前根连接一条到根的链. 然后考虑假若最大导出子树深度为 \(n\) 则显然可以把深度为 \(n\) 的节点全部选上,然后每个节 ...
- SpringBoot快速插入Mysql 1000万条数据
导读 有时候为了验证系统瓶颈,需要往数据库表中插入大量数据,可以写sheel脚本插入,前几天为了插入100万条数据,走的sheel脚本(点我直达),插入速度简直无法直视,花了3小时,才插入了10万条, ...
- sshd管理限制登录配置(centos7.9)
背景情况:为了公网的主机,被无限的密码爆破,需要对主机的ssh进行安装加固 1.首先要禁用root的远程登录和修改ssh的端口 vi /etc/ssh/sshd_config# 修改端口,不适用22端 ...