图像基本概念

在图像数字化表示当中,分为黑白和彩色两种。在数字化表示图片的时候,有三个因素。分别是图片的长、图片的宽、图片的颜色通道数。那么黑白图片的颜色通道数为1,它只需要一个数字就可以表示一个像素位;而彩色照片就不一样了,它有三个颜色通道,分别为RGB,通过三个数字表示一个像素位。TensorFlow支持JPG、PNG图像格式,RGB、RGBA颜色空间。图像用与图像尺寸相同(height*width*chnanel)张量表示。图像所有像素存在磁盘文件,需要被加载到内存。

图像基本操作

目的:

  1. 增加图片数据的统一性
  2. 所有图片转换成指定大小
  3. 缩小图片数据量,防止增加开销

操作:

  1. 缩小图片大小

图像基本操作API

tf.image.resize_images(images, size):缩小图片

  • images:4-D形状[batch, height, width, channels]或3-D形状的张量[height, width, channels]的图片数据
  • size:1-D int32张量:new_height, new_width,图像的新尺寸
  • 返回4-D格式或者3-D格式图片

图像读取API

图像读取器:

tf.WholeFileReader:将文件的全部内容作为值输出的读取器

  • return:读取器实例
  • read(file_queue):输出将是一个文件名(key)和该文件的内容(值)

图像解码器:

tf.image.decode_jpeg(contents):将JPEG编码的图像解码为uint8张量

  • return:uint8张量,3-D形状[height, width, channels]

tf.image.decode_png(contents):将PNG编码的图像解码为uint8或uint16张量

  • return:张量类型,3-D形状[height, width, channels]

狗图片读取

  1. import tensorflow as tf
  2. import os
  3. def readpic(filelist):
  4. """
  5. 狗图片读取
  6. """
  7. # 构建文件队列
  8. file_queue = tf.train.string_input_producer(filelist)
  9. # 构造阅读器
  10. reader = tf.WholeFileReader()
  11. key, value = reader.read(file_queue)
  12. print(value)
  13. # 对读取到的图片进行解码
  14. image = tf.image.decode_jpeg(value)
  15. print(image)
  16. # 处理图片的大小
  17. img_resize = tf.image.resize_images(image, [250, 250])
  18. print(img_resize)
  19. img_resize.set_shape([250, 250, 3])
  20. # 批处理
  21. image_batch = tf.train.batch([img_resize], batch_size=10, num_threads=1, capacity=10)
  22. print(image_batch)
  23. return image_batch
  24. if __name__ == '__main__':
  25. filelist = os.listdir("./data/dogs")
  26. filelist = ["./data/dogs/{}".format(i) for i in filelist]
  27. image_batch = readpic(filelist)
  28. with tf.Session() as sess:
  29. # 线程协调器
  30. coord = tf.train.Coordinator()
  31. # 开启读取文件线程
  32. threads = tf.train.start_queue_runners(sess, coord=coord)
  33. # 打印数据
  34. print(sess.run([image_batch]))
  35. coord.request_stop()
  36. coord.join()

案例流程:

  • 构造图片文件队列
  • 构造阅读器
  • 读取图片数据
  • 处理图片数据

CIFAR-10二进制数据读取

网站:https://www.cs.toronto.edu/~kriz/cifar.html

  1. import tensorflow as tf
  2. import os
  3. # 定义cifar命令相关参数
  4. tf.app.flags.DEFINE_string("cifar_dir", "./data/cifar-10-batches-bin", "cifar目录")
  5. FLAGS = tf.app.flags.FLAGS
  6. class CifarReader(object):
  7. """
  8. 读取二进制文件,写入tfrecords,读取tfrecords
  9. """
  10. def __init__(self, filelist):
  11. self.filelist = filelist
  12. # 定义读取的二进制图片的一些属性
  13. self.width = 32
  14. self.height = 32
  15. self.channel = 3
  16. self.label_bytes = 1
  17. self.image_bytes = self.width * self.height * self.channel
  18. self.bytes = self.label_bytes + self.image_bytes
  19. def read_and_decode(self):
  20. # 构造文件队列
  21. file_queue = tf.train.string_input_producer(self.filelist)
  22. # 构造二进制文件阅读器
  23. reader = tf.FixedLengthRecordReader(self.bytes)
  24. key, value = reader.read(file_queue)
  25. # 解码
  26. label_image = tf.decode_raw(value, tf.uint8)
  27. print(label_image)
  28. # 分离出图片和标签数据
  29. label = tf.cast(tf.slice(label_image, [0], [self.label_bytes]), tf.int32)
  30. image = tf.slice(label_image, [self.label_bytes], [self.image_bytes])
  31. # 改变图片的形状 [3072] -> [32, 32, 3]
  32. image_reshape = tf.reshape(image, [self.height, self.width, self.channel])
  33. print(label, image_reshape)
  34. # 批处理数据
  35. label_batch, image_batch = tf.train.batch([label, image_reshape], batch_size=20, num_threads=1, capacity=20)
  36. print(label_batch, image_batch)
  37. return label_batch, image_batch
  38. if __name__ == '__main__':
  39. filelist = os.listdir(FLAGS.cifar_dir)
  40. filelist = [os.path.join(FLAGS.cifar_dir, i) for i in filelist if i.endswith(".bin")]
  41. cf = CifarReader(filelist)
  42. label_batch, image_batch = cf.read_and_decode()
  43. with tf.Session() as sess:
  44. # 线程协调器
  45. coord = tf.train.Coordinator()
  46. # 开启读取文件线程
  47. threads = tf.train.start_queue_runners(sess, coord=coord)
  48. # 打印数据
  49. print(sess.run([label_batch, image_batch]))
  50. coord.request_stop()
  51. coord.join()

TFRecords

TFRecords是Tensorflow设计的一种内置文件格式,是一种二进制文件,它能更好的利用内存,更方便复制和移动。为了将二进制数据和标签(训练的类别标签)数据存储在同一个文件中。

TFRecords存储

  1. 建立TFRecord存储器:tf.python_io.TFRecordWriter(path)

    • path: TFRecords文件的路径
    • return:写文件
    • 方法:
      • write(record):向文件中写入一个字符串记录
      • close():关闭文件写入器
    • 注:字符串是一个序列化的Example:Example.SerializeToString()
  2. 构造每个样本的Example协议块
    • tf.train.Example(features=None)

      • 写入tfrecords文件
      • features:tf.train.Features类型的特征实例
      • return:example格式协议块
    • tf.train.Features(feature=None)
      • 构建每个样本的信息键值对
      • features:字典数据,key为要保存的名字,value为tf.train.Feature实例
      • return:Features类型
    • tf.train.Feature(**options)
      • **options:例如:

        bytes_list=tf.train. BytesList(value=[Bytes])

        int64_list=tf.train. Int64List(value=[Value])

对于上例中【CIFAR-10二进制数据读取】读取到的数据进行存储:

  1. import tensorflow as tf
  2. import os
  3. # 定义cifar命令相关参数
  4. tf.app.flags.DEFINE_string("cifar_dir", "./data/cifar-10-batches-bin", "cifar目录")
  5. tf.app.flags.DEFINE_string("cifar_tfrecords", "./temp/cifar.tfrecords", "保存的tfrecords文件路径")
  6. FLAGS = tf.app.flags.FLAGS
  7. class CifarReader(object):
  8. """
  9. 读取二进制文件,写入tfrecords,读取tfrecords
  10. """
  11. def __init__(self, filelist):
  12. self.filelist = filelist
  13. # 定义读取的二进制图片的一些属性
  14. self.width = 32
  15. self.height = 32
  16. self.channel = 3
  17. self.label_bytes = 1
  18. self.image_bytes = self.width * self.height * self.channel
  19. self.bytes = self.label_bytes + self.image_bytes
  20. def read_and_decode(self):
  21. # 构造文件队列
  22. file_queue = tf.train.string_input_producer(self.filelist)
  23. # 构造二进制文件阅读器
  24. reader = tf.FixedLengthRecordReader(self.bytes)
  25. key, value = reader.read(file_queue)
  26. # 解码
  27. label_image = tf.decode_raw(value, tf.uint8)
  28. print(label_image)
  29. # 分离出图片和标签数据
  30. label = tf.cast(tf.slice(label_image, [0], [self.label_bytes]), tf.int32)
  31. image = tf.slice(label_image, [self.label_bytes], [self.image_bytes])
  32. # 改变图片的形状 [3072] -> [32, 32, 3]
  33. image_reshape = tf.reshape(image, [self.height, self.width, self.channel])
  34. print(label, image_reshape)
  35. # 批处理数据
  36. label_batch, image_batch = tf.train.batch([label, image_reshape], batch_size=20, num_threads=1, capacity=20)
  37. print(label_batch, image_batch)
  38. return label_batch, image_batch
  39. def write_to_tfrecords(self, label_batch, image_batch):
  40. """
  41. 存储图片的目标值和特征值
  42. :param label_batch: 图片的目标值
  43. :param image_batch: 图片的特征值
  44. :return: None
  45. """
  46. # 建立tfrecords存储器
  47. writer = tf.python_io.TFRecordWriter(FLAGS.cifar_tfrecords)
  48. # 将所有样本写入文件
  49. for i in range(label_batch.shape[0]):
  50. label = int(label_batch[i].eval()[0])
  51. image = image_batch[i].eval().tostring()
  52. example = tf.train.Example(features=tf.train.Features(feature={
  53. "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
  54. "image": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image]))
  55. }))
  56. writer.write(example.SerializeToString())
  57. writer.close()
  58. if __name__ == '__main__':
  59. filelist = os.listdir(FLAGS.cifar_dir)
  60. filelist = [os.path.join(FLAGS.cifar_dir, i) for i in filelist if i.endswith(".bin")]
  61. cf = CifarReader(filelist)
  62. label_batch, image_batch = cf.read_and_decode()
  63. with tf.Session() as sess:
  64. # 线程协调器
  65. coord = tf.train.Coordinator()
  66. # 开启读取文件线程
  67. threads = tf.train.start_queue_runners(sess, coord=coord)
  68. # 存为tfrecords文件
  69. cf.write_to_tfrecords(label_batch, image_batch)
  70. # 打印数据
  71. print(sess.run([label_batch, image_batch]))
  72. coord.request_stop()
  73. coord.join()

TFRecords读取方法

同文件阅读器流程,中间需要解析过程

解析TFRecords的example协议内存块:

  • tf.parse_single_example(serialized,features=None,name=None)

    • 解析一个单一的Example原型
    • serialized:标量字符串Tensor,一个序列化的Example
    • features:dict字典数据,键为读取的名字,值为FixedLenFeature
    • return:一个键值对组成的字典,键为读取的名字
  • tf.FixedLenFeature(shape,dtype)
    • shape:输入数据的形状,一般不指定,为空列表
    • dtype:输入数据类型,与存储进文件的类型要一致,类型只能是float32,int64,string

读取上例保存的tfrecords文件:

  1. # 定义cifar命令相关参数
  2. tf.app.flags.DEFINE_string("cifar_dir", "./data/cifar-10-batches-bin", "cifar目录")
  3. tf.app.flags.DEFINE_string("cifar_tfrecords", "./temp/cifar.tfrecords", "保存的tfrecords文件路径")
  4. FLAGS = tf.app.flags.FLAGS
  5. class CifarReader(object):
  6. """
  7. 读取二进制文件,写入tfrecords,读取tfrecords
  8. """
  9. def __init__(self, filelist):
  10. self.filelist = filelist
  11. # 定义读取的二进制图片的一些属性
  12. self.width = 32
  13. self.height = 32
  14. self.channel = 3
  15. self.label_bytes = 1
  16. self.image_bytes = self.width * self.height * self.channel
  17. self.bytes = self.label_bytes + self.image_bytes
  18. def read_from_cfrecords(self):
  19. """
  20. 读取cfrecords
  21. :return: None
  22. """
  23. # 构建文件队列
  24. file_queue = tf.train.string_input_producer([FLAGS.cifar_tfrecords])
  25. # 构建文件阅读器
  26. reader = tf.TFRecordReader()
  27. key, value = reader.read(file_queue)
  28. # 解析example
  29. features = tf.parse_single_example(value, features={
  30. "label": tf.FixedLenFeature([], tf.int64),
  31. "image": tf.FixedLenFeature([], tf.string)
  32. })
  33. # 解码
  34. image = tf.decode_raw(features["image"], tf.uint8)
  35. image_reshape = tf.reshape(image, [self.height, self.width, self.channel])
  36. label = tf.cast(features["label"], tf.int32)
  37. print(label, image_reshape)
  38. # 批处理
  39. label_batch, image_batch = tf.train.batch([label, image_reshape], batch_size=20, num_threads=1, capacity=20)
  40. print(label_batch, image_reshape)
  41. return label_batch, image_reshape
  42. if __name__ == '__main__':
  43. label_batch, image_batch = cf.read_from_cfrecords()
  44. with tf.Session() as sess:
  45. # 线程协调器
  46. coord = tf.train.Coordinator()
  47. # 开启读取文件线程
  48. threads = tf.train.start_queue_runners(sess, coord=coord)
  49. # 打印数据
  50. print(sess.run([label_batch, image_batch]))
  51. coord.request_stop()
  52. coord.join()

【学习笔记】tensorflow图片读取的更多相关文章

  1. [置顶] iOS学习笔记47——图片异步加载之EGOImageLoading

    上次在<iOS学习笔记46——图片异步加载之SDWebImage>中介绍过一个开源的图片异步加载库,今天来介绍另外一个功能类似的EGOImageLoading,看名字知道,之前的一篇学习笔 ...

  2. Webpack4 学习笔记五 图片解析、输出的文件划分目录

    前言 此内容是个人学习笔记,以便日后翻阅.非教程,如有错误还请指出 webpack打包图片和划分文件路径 使用图片的方式 通过 new Image() 在 css中设置 background-imag ...

  3. [Python学习笔记]文件的读取写入

    文件与文件路径 路径合成 os.path.join() 在Windows上,路径中以倒斜杠作为文件夹之间的分隔符,Linux或OS X中则是正斜杠.如果想要程序正确运行于所有操作系统上,就必须要处理这 ...

  4. Android学习笔记之图片轮播...

    PS:一个bug又折腾了一个下午....哎... 学习内容: 1.Android利用ViewPager和PagerAdapter实现图片轮播... 2.使用反射机制获取Android的资源信息... ...

  5. TensorFlow 深度学习笔记 TensorFlow实现与优化深度神经网络

    转载请注明作者:梦里风林 Github工程地址:https://github.com/ahangchen/GDLnotes 欢迎star,有问题可以到Issue区讨论 官方教程地址 视频/字幕下载 全 ...

  6. tensorflow学习笔记----tensorflow在windows的安装及TensorBoard中mnist样例

    前言:                                                                                                 ...

  7. 3.2html学习笔记之图片

    <img src="" width="50%" alt="加载时候或无法显示时候显示的文字" height="让浏览器预先给 ...

  8. css3学习笔记之图片

    圆角图片 border-radius: 圆角图片: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <!DOCTYPE html> <htm ...

  9. [转载]mongoDB学习笔记——存取图片(C#)

    作为一个NoSql数据库的代表,存取多媒体数据,应该是强项吧?那么,图片在mongoDB里是如何存取的呢?(其实,关系型数据库存取图片也一点问题没有,所以我看NoSql的强项不在于是否存储多媒体,而在 ...

随机推荐

  1. Restful levels&HATEOAS

    RESTful: Rest是一种软件架构风格.设计风格,而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等 ...

  2. HTTPS 原理浅析及其在 Android 中的使用

    作者:曹丰斌   本文首先分析HTTP协议在安全性上的不足,进而阐述HTTPS实现安全通信的关键技术点和原理.然后通过抓包分析HTTPS协议的握手以及通信过程.最后总结一下自己在开发过程中遇到的HTT ...

  3. 微信小程序wx.request请求用POST后台得不到传递数据

    微信小程序的wx.request请求,method设为POST并向后台传递数据,但从后台返回的信息来看后台并没有获得传递的数据 wx.request({              url: 'url' ...

  4. GT-随身调详细教程

    一.GT介绍 GT(随身调)是APP的随身调测平台,它是直接运行在手机上的“集成调测环境”(IDTE, Integrated Debug Environment).利用GT,仅凭一部手机,无需连接电脑 ...

  5. vue中实现动态切换不同的值

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. [Swift]LeetCode661. 图片平滑器 | Image Smoother

    Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother t ...

  7. [Swift]LeetCode676. 实现一个魔法字典 | Implement Magic Dictionary

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  8. Spring Boot 最核心的 25 个注解,都是干货!

    学习和应用 Spring Boot 有一些时间了,你们对 Spring Boot 注解了解有多少呢?今天栈长我给大家整理了 Spring Boot 最核心的 25 个注解,都是干货! 你所需具备的基础 ...

  9. ReentrantLock 实现原理

    使用 synchronize 来做同步处理时,锁的获取和释放都是隐式的,实现的原理是通过编译后加上不同的机器指令来实现. 而 ReentrantLock 就是一个普通的类,它是基于 AQS(Abstr ...

  10. knockoutjs 上自己实现的flux

    在knockoutjs 上实现 Flux 单向数据流 状态机,主要解决多个组件之间对数据的耦合问题. 一.其实简单 flux的设计理念和实现方案,很大程度上人借鉴和参考了Vuex的实现,只是简化了某些 ...