TensorFlowIO操作(三)------图像操作
图像操作
图像基本概念
在图像数字化表示当中,分为黑白和彩色两种。在数字化表示图片的时候,有三个因素。分别是图片的长、图片的宽、图片的颜色通道数。那么黑白图片的颜色通道数为1,它只需要一个数字就可以表示一个像素位;而彩色照片就不一样了,它有三个颜色通道,分别为RGB,通过三个数字表示一个像素位。TensorFlow支持JPG、PNG图像格式,RGB、RGBA颜色空间。图像用与图像尺寸相同(heightwidthchnanel)张量表示。图像所有像素存在磁盘文件,需要被加载到内存。
图像大小压缩
大尺寸图像输入占用大量系统内存。训练CNN需要大量时间,加载大文件增加更多训练时间,也难存放多数系统GPU显存。大尺寸图像大量无关本征属性信息,影响模型泛化能力。最好在预处理阶段完成图像操作,缩小、裁剪、缩放、灰度调整等。图像加载后,翻转、扭曲,使输入网络训练信息多样化,缓解过拟合。Python图像处理框架PIL、OpenCV。TensorFlow提供部分图像处理方法。
- tf.image.resize_images 压缩图片导致定大小
图像数据读取实例
同样图像加载与二进制文件相同。图像需要解码。输入生成器(tf.train.string_input_producer)找到所需文件,加载到队列。tf.WholeFileReader 加载完整图像文件到内存,WholeFileReader.read 读取图像,tf.image.decode_jpeg 解码JPEG格式图像。图像是三阶张量。RGB值是一阶张量。加载图像格 式为[batch_size,image_height,image_width,channels]。批数据图像过大过多,占用内存过高,系统会停止响应。直接加载TFRecord文件,可以节省训练时间。支持写入多个样本。
读取图片数据到Tensor
管道读端多文件内容处理
但是会发现read只返回一个图片的值。所以我们在之前处理文件的整个流程中,后面的内容队列的出队列需要用特定函数去获取。
- tf.train.batch 读取指定大小(个数)的张量
- tf.train.shuffle_batch 乱序读取指定大小(个数)的张量
def readpic_decode(file_list):
"""
批量读取图片并转换成张量格式
:param file_list: 文件名目录列表
:return: None
""" # 构造文件队列
file_queue = tf.train.string_input_producer(file_list) # 图片阅读器和读取数据
reader = tf.WholeFileReader()
key,value = reader.read(file_queue) # 解码成张量形式 image_first = tf.image.decode_jpeg(value) print(image_first) # 缩小图片到指定长宽,不用指定通道数
image = tf.image.resize_images(image_first,[256,256]) # 设置图片的静态形状
image.set_shape([256,256,3]) print(image) # 批处理图片数据,tensors是需要具体的形状大小
image_batch = tf.train.batch([image],batch_size=100,num_threads=1,capacity=100) tf.summary.image("pic",image_batch) with tf.Session() as sess: merged = tf.summary.merge_all() filewriter = tf.summary.FileWriter("/tmp/summary/dog/",graph=sess.graph) # 线程协调器
coord = tf.train.Coordinator() # 开启线程
threads = tf.train.start_queue_runners(sess=sess,coord=coord) print(sess.run(image_batch)) summary = sess.run(merged) filewriter.add_summary(summary) # 等待线程回收
coord.request_stop()
coord.join(threads) return None if __name__=="__main__": # 获取文件列表
filename = os.listdir("./dog/") # 组合文件目录和文件名
file_list = [os.path.join("./dog/",file) for file in filename] # 调用读取函数
readpic_decode(file_list)
读取TfRecords文件数据
#CIFAR-10的数据读取以及转换成TFRecordsg格式 #1、数据的读取 FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("data_dir","./cifar10/cifar-10-batches-bin/","CIFAR数据目录")
tf.app.flags.DEFINE_integer("batch_size",50000,"样本个数")
tf.app.flags.DEFINE_string("records_file","./cifar10/cifar.tfrecords","tfrecords文件位置") class CifarRead(object): def __init__(self,filename):
self.filelist = filename # 定义图片的长、宽、深度,标签字节,图像字节,总字节数
self.height = 32
self.width = 32
self.depth = 3
self.label_bytes = 1
self.image_bytes = self.height*self.width*self.depth
self.bytes = self.label_bytes + self.image_bytes def readcifar_decode(self):
"""
读取数据,进行转换
:return: 批处理的图片和标签
""" # 1、构造文件队列
file_queue = tf.train.string_input_producer(self.filelist) # 2、构造读取器,读取内容
reader = tf.FixedLengthRecordReader(self.bytes) key,value = reader.read(file_queue) # 3、文件内容解码
image_label = tf.decode_raw(value,tf.uint8) # 分割标签与图像张量,转换成相应的格式 label = tf.cast(tf.slice(image_label,[0],[self.label_bytes]),tf.int32) image = tf.slice(image_label,[self.label_bytes],[self.image_bytes]) print(image) # 给image设置形状,防止批处理出错
image_tensor = tf.reshape(image,[self.height,self.width,self.depth]) print(image_tensor.eval())
# depth_major = tf.reshape(image, [self.depth,self.height, self.width])
# image_tensor = tf.transpose(depth_major, [1, 2, 0]) # 4、处理流程
image_batch,label_batch = tf.train.batch([image_tensor,label],batch_size=10,num_threads=1,capacity=10) return image_batch,label_batch def convert_to_tfrecords(self,image_batch,label_batch):
"""
转换成TFRecords文件
:param image_batch: 图片数据Tensor
:param label_batch: 标签数据Tensor
:param sess: 会话
:return: None
""" # 创建一个TFRecord存储器
writer = tf.python_io.TFRecordWriter(FLAGS.records_file) # 构造每个样本的Example
for i in range(10):
print("---------")
image = image_batch[i]
# 将单个图片张量转换为字符串,以可以存进二进制文件
image_string = image.eval().tostring() # 使用eval需要注意的是,必须存在会话上下文环境
label = int(label_batch[i].eval()[0]) # 构造协议块
example = tf.train.Example(features=tf.train.Features(feature={
"image": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_string])),
"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))
})
) # 写进文件
writer.write(example.SerializeToString()) writer.close() return None def read_from_tfrecords(self):
"""
读取tfrecords
:return: None
"""
file_queue = tf.train.string_input_producer(["./cifar10/cifar.tfrecords"]) reader = tf.TFRecordReader() key, value = reader.read(file_queue) features = tf.parse_single_example(value, features={
"image":tf.FixedLenFeature([], tf.string),
"label":tf.FixedLenFeature([], tf.int64),
}) image = tf.decode_raw(features["image"], tf.uint8) # 设置静态形状,可用于转换动态形状
image.set_shape([self.image_bytes]) print(image) image_tensor = tf.reshape(image,[self.height,self.width,self.depth]) print(image_tensor) label = tf.cast(features["label"], tf.int32) print(label) image_batch, label_batch = tf.train.batch([image_tensor, label],batch_size=10,num_threads=1,capacity=10)
print(image_batch)
print(label_batch) with tf.Session() as sess:
coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess,coord=coord) print(sess.run([image_batch, label_batch])) coord.request_stop()
coord.join(threads) return None if __name__=="__main__":
# 构造文件名字的列表
filename = os.listdir(FLAGS.data_dir)
file_list = [os.path.join(FLAGS.data_dir, file) for file in filename if file[-3:] == "bin"] cfar = CifarRead(file_list)
# image_batch,label_batch = cfar.readcifar_decode()
cfar.read_from_tfrecords() with tf.Session() as sess: # 构建线程协调器
coord = tf.train.Coordinator() # 开启线程
threads = tf.train.start_queue_runners(sess=sess, coord=coord) # print(sess.run(image_batch)) # 存进文件
# cfar.convert_to_tfrecords(image_batch, label_batch) coord.request_stop()
coord.join(threads)
TensorFlowIO操作(三)------图像操作的更多相关文章
- {MySQL的库、表的详细操作}一 库操作 二 表操作 三 行操作
MySQL的库.表的详细操作 MySQL数据库 本节目录 一 库操作 二 表操作 三 行操作 一 库操作 1.创建数据库 1.1 语法 CREATE DATABASE 数据库名 charset utf ...
- HT for Web基于HTML5的图像操作(三)
上篇采用了HTML5的Canvas的globalCompositeOperation属性达到了染色效果,其实CSS也提供了一些常规图像变化的设置参数,关于CSS的过滤器Filter设置可参考 http ...
- Python用Pillow(PIL)进行简单的图像操作
Python用Pillow(PIL)进行简单的图像操作 颜色与RGBA值 计算机通常将图像表示为RGB值,或者再加上alpha值(通透度,透明度),称为RGBA值.在Pillow中,RGBA的值表示为 ...
- Tensorflow图像操作
图像操作 图像基本概念 在图像数字化表示当中,分为黑白和彩色两种.在数字化表示图片的时候,有三个因素.分别是图片的长.图片的宽.图片的颜色通道数.那么黑白图片的颜色通道数为1,它只需要一个数字就可以表 ...
- GIS基础软件及操作(三)
原文 GIS基础软件及操作(三) 练习三.地图配准操作 1.对无坐标信息的地形图(图片格式)进行地图配准操作2.编辑器的使用(点要素.线要素.多边形要素的数字化) 本例主要介绍如何给无坐标信息的地形图 ...
- 基本图像操作和处理(python)
基本图像操作和处理(python) PIL提供了通用的图像处理功能,以及大量的基本图像操作,如图像缩放.裁剪.旋转.颜色转换等. Matplotlib提供了强大的绘图功能,其下的pylab/pyplo ...
- PHP核心编程-图像操作
一 图像操作环境: 1. 开启GD2图像处理并检测 在php.ini开启GD库 2. 画布坐标系说明 二. 图像基本操作(步骤) 1. 创建图像 创建画布(图像资源) 创建的方法: ...
- python进阶—OpenCV之常用图像操作函数说明(转)
文章目录cv2.thresholdcv2.bitwise_andcv2.bitwise_orcv2.bitwise_notcv2.inRangecv2.resizecv2.adaptiveThresh ...
- 学习PHP中好玩的Gmagick图像操作扩展的使用
在 PHP 的图像处理领域,要说最出名的 GD 库为什么好,那就是因为它不需要额外安装的别的什么图像处理工具,而且是随 PHP 源码一起发布的,只需要在安装 PHP 的时候添加上编译参数就可以了. G ...
随机推荐
- TestDirector自定义管理:用户配置
一.进入Customize 1.打开TD,点击TestDirector,进入登录界面,在TD登录页面右上角点击“CUSTOMIZE(自定义)”. 2.选择要登录的域和项目,输入用户帐号和密码,点击确定 ...
- linux 笔记(一)
1.Linux 安装3ython3 1.1 下载 wget https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz 1.2 解压 tar -z ...
- 导出php5.4支持的数组格式,即以[]为标识符而不是以array()标识
//导出php数组,以[]为标识符而不是以array() if (!function_exists('varExport')) { //导出php数组,以[]为标识符而不是以array() funct ...
- 转:Heap spraying high addresses in 32-bit Chrome/Firefox on 64-bit Windows
转:https://blog.skylined.nl/20160622001.html,June 22nd, 2016 In my previous blog post I wrote about m ...
- Django+Nginx+uwsgi搭建自己的博客(七)
上一篇博客中介绍了Blogs App的部分后端功能的实现,在这篇博客中,将继续为大家介绍Blogs App中前端功能的实现. 首先来看发布博客功能的前端页面.在blogs/templates/blog ...
- POJ 3228 [并查集]
题目链接:[http://poj.org/problem?id=3228] 题意:给出n个村庄,每个村庄有金矿和仓库,然后给出m条边连接着这个村子.问题是把所有的金矿都移动到仓库里所要经过的路径的最大 ...
- codevs 1392 合并傻子
1392 合并傻子 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description 在一个园形操场的四周站着N个傻子,现要将傻子有 ...
- 【洛谷】P1063 能量项链【区间DP】
P1063 能量项链 题目描述 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾标记的珠子,这些标记对应着某个正整数.并且,对于相邻的两颗珠子, ...
- bzoj 3784
第三道点分治. 首先找到黄学长的题解,他叫我参考XXX的题解,但已经没有了,然后找到另一个博客的简略题解,没看懂,最后看了一个晚上黄学长代码,写出来然后,写暴力都拍了小数据,但居然超时,....然后改 ...
- ZOJ 1015 弦图判定
一些定义: 弦图是一种特殊图:它的所有极小环都只有3个顶点. 单纯点:该顶点与其邻接点在原图中的导出子图是一个完全图. 图G的完美消去序列:一个顶点序列a1a2a3...an,使得对于每个元素ai,a ...