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 方法 (示例)的更多相关文章

  1. TensorFlow中读取图像数据的三种方式

    本文面对三种常常遇到的情况,总结三种读取数据的方式,分别用于处理单张图片.大量图片,和TFRecorder读取方式.并且还补充了功能相近的tf函数. 1.处理单张图片 我们训练完模型之后,常常要用图片 ...

  2. Tensorflow 处理libsvm格式数据生成TFRecord (parse libsvm data to TFRecord)

    #写libsvm格式 数据 write libsvm     #!/usr/bin/env python #coding=gbk # ================================= ...

  3. Oracle在本地调试成功读取数据,但是把代码放到服务器读不出数据的解决方法。

    用MVC EF框架开发项目,数据库用的是Oracle,本地调试的时候一切正常,但是把代码编译之后放到服务器就会读不出数据. 原因:本地调试环境与服务器环境不一致. 办法:在服务器上装ODT.NET组件 ...

  4. 快速遍历OpenCV Mat图像数据的多种方法和性能分析 | opencv mat for loop

    本文首发于个人博客https://kezunlin.me/post/61d55ab4/,欢迎阅读! opencv mat for loop Series Part 1: compile opencv ...

  5. Delphi存取图像完整解决方案

    http://blog.sina.com.cn/s/blog_693cf1cf0100plkq.html 对于涉及图像数据的数据库应用程序,图像数据的存取技术是一个关键.由于缺少技术文档及DEMO例程 ...

  6. Inter IPP 处理图像数据的方法

    Inter IPP没有读取图片和保存图片的函数,需要结合opencv完成这个功能. opencv读到图片以后逐个像素点赋值给IPP显然是不可取的,方法如下: int main(int argc, ch ...

  7. vc/mfc获取rgb图像数据后动态显示及保存图片的方法

    vc/mfc获取rgb图像数据后动态显示及保存图片的方法 该情况可用于视频通信中获取的位图数据回放显示或显示摄像头捕获的本地图像 第一种方法 #include<vfw.h> 加载 vfw3 ...

  8. [转]MFC子线程更改图像数据后更新主窗口图像显示方法

    程序思路是由外部的输入输出控制卡发出采集图像信号,之后相机采集图像得到图像数据指针,接收图像数据指针创建成图像最后显示到MFC对话框应用程序的Picture Control控件上,同时,为了标定相机位 ...

  9. (转)原始图像数据和PDF中的图像数据

    比较原始图像数据和PDF中的图像数据,结果见表1.1.表1.1中各种“解码器”的解释见本文后续的“PDF支持的图像格式”部分,“PDF中的图像数据”各栏中的数据来自开源的PdfView.如果您有兴趣查 ...

  10. 基于FPGA的Uart接收图像数据至VGA显示

    系统框图 前面我们设计了基于FPGA的静态图片显示,接下来我们来做做基于FPGA的动态图片显示,本实验内容为:由PC端上位机软件通过串口发送一幅图像数据至FPGA,FPGA内部将图像数据存储,最后扫描 ...

随机推荐

  1. SpringBoot系列(二) 环境搭建,创建我的第一个程序HelloWord。

    环境准备: jdk1.8:java version "1.8.0_231",详见链接 maven3.x:maven3.3以上版本,详见链接 IDEA2021:IntelliJ ID ...

  2. Prometheus + Grafana (1) 监控

    简介 Micrometer/Prometheus/Grafana体系是当前最成熟的低成本Java监控解决方案,而且通过其他的Prometheus exporter,还可以进行诸如我们可能需要的Wind ...

  3. navicat 15

    新机经常需要安装navicat每次都要去网上搜很麻烦这次搜到了记录下来以后就不需要重复下载了 有X86和X64两个版本 破解说明在README文档中 下载地址:https://www.aliyundr ...

  4. C# DateTime日期字段转中文文字

    public static String ToChineseYearAndMonth(this DateTime dt) { string[] chineseNumbers = { "零&q ...

  5. 2019 香港区域赛 BDEG 题解

    B.Binary Tree 题意:给你一棵二叉树.有两个游戏者,回合制,他们每次可以删去这棵二叉树中的一棵满二叉树.求最后谁赢. 解法:每一棵满二叉树有奇数个节点,那么每次游戏者只能删去奇数个节点,所 ...

  6. ODPS 不用循环生成连续日期

    生成 20230801 ~ 20230831之间的每一天的sql代码怎么写? 只要一行代码. 一行代码: select TO_CHAR(DATEADD(TO_DATE(bizdate,'yyyymmd ...

  7. 安卓Camera-HAL显示值与比例

    安卓Camera-HAL显示值与比例 参考:https://blog.csdn.net/wang714818/article/details/78049649?utm_source=blogxgwz4 ...

  8. 使用iperf3调试网络

    介绍 Iperf是一款基于TCP/IP和UDP/IP的网络性能测试工具,它可以用来测量网络带宽和网络质量,还可以提供网络延迟抖动.数据包丢失率.最大传输单元等统计信息.网络管理员可以根据这些信息了解并 ...

  9. STM32 CubeMX 学习:06-配置DMA

    --- title: mcu-stm32-cube-06-配置DMA date: 2020-05-31 16:39:05 categories: tags: - stm32 - cubeMx - dm ...

  10. MySql 安装详细步骤

    一.官网下载 官网地址:https://dev.mysql.com/downloads/installer/ 二.开始安装 1.点击按装文件开始安装 2.只安装服务端就可以了,一直下一步 3. 4. ...