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 ...
随机推荐
- Spark 源码解析 : DAGScheduler中的DAG划分与提交
一.Spark 运行架构 Spark 运行架构如下图: 各个RDD之间存在着依赖关系,这些依赖关系形成有向无环图DAG,DAGScheduler对这些依赖关系形成的DAG,进行Stage划分,划分的规 ...
- HTML如何创建二级目录
#classify ul li div{width:100px; height:200px; display:none; position:absolute; left:100px; top ...
- vue-router history 模式 iis 配置
首先需要安装 url rewrite模块到IIS点我安装 然后在web.config文件中添加如下配置 <?xml version="1.0" encoding=" ...
- 洛谷P1726 上白泽慧音 [Tarjan]
题目传送门 上白泽慧音 题目描述 在幻想乡,上白泽慧音是以知识渊博闻名的老师.春雪异变导致人间之里的很多道路都被大雪堵塞,使有的学生不能顺利地到达慧音所在的村庄.因此慧音决定换一个能够聚集最多人数的村 ...
- PBR Step by Step(三)BRDFs
BRDF BRDF(Bidirectional Reflectance Distribution Function)双向反射分布函数,用来描述给定入射方向上的入射辐射度以及反射方向上的出辐射度分布,B ...
- CF400C/[思维题]
题目链接http://codeforces.com/problemset/problem/400/C 题意:给出一个(N,M)矩形和矩形里的p(p<=1e5)个点坐标,然后顺时针旋转x,镜面对称 ...
- 【BZOJ 2460】线性基
2460: [BeiJing2011]元素 Description 相传,在远古时期,位于西方大陆的 Magic Land 上,人们已经掌握了用魔法矿石炼制法杖的技术.那时人们就认识到,一个法杖的法力 ...
- ARGB 8888 内存大小
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha 4字节 argb 各占8个bit
- [SPOJ SEQN] [hdu3439]Sequence
题目就是求C(n,k)*H(n - k)%m 0<= k<= n <=10^9, 1 <= m <= 10^5, n != 0 其中H(n)是错排第n项. 对于C(n,k ...
- HDU 6119 小小粉丝度度熊(Two pointers)
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6119 [题目大意] 给出一些签到区间和一些补签卡,问可以创造的最长连续签到区间 [题解] 如果我们 ...