TensorFLow 不同大小图片的TFrecords存取实例

 更新时间:2020年4月22日 23:19  点击:1976

全部存入一个TFrecords文件,然后读取并显示第一张。

不多写了,直接贴代码。

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf


IMAGE_PATH = 'test/'
tfrecord_file = IMAGE_PATH + 'test.tfrecord'
writer = tf.python_io.TFRecordWriter(tfrecord_file)


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]))

def get_image_binary(filename):
  """ You can read in the image using tensorflow too, but it's a drag
    since you have to create graphs. It's much easier using Pillow and NumPy
  """
  image = Image.open(filename)
  image = np.asarray(image, np.uint8)
  shape = np.array(image.shape, np.int32)
  return shape, image.tobytes() # convert image to raw data bytes in the array.

def write_to_tfrecord(label, shape, binary_image, tfrecord_file):
  """ This example is to write a sample to TFRecord file. If you want to write
  more samples, just use a loop.
  """
  # write label, shape, and image content to the TFRecord file
  example = tf.train.Example(features=tf.train.Features(feature={
        'label': _int64_feature(label),
        'h': _int64_feature(shape[0]),
        'w': _int64_feature(shape[1]),
        'c': _int64_feature(shape[2]),
        'image': _bytes_feature(binary_image)
        }))
  writer.write(example.SerializeToString())


def write_tfrecord(label, image_file, tfrecord_file):
  shape, binary_image = get_image_binary(image_file)
  write_to_tfrecord(label, shape, binary_image, tfrecord_file)
  # print(shape)



def main():
  # assume the image has the label Chihuahua, which corresponds to class number 1
  label = [1,2]
  image_files = [IMAGE_PATH + 'a.jpg', IMAGE_PATH + 'b.jpg']

  for i in range(2):
    write_tfrecord(label[i], image_files[i], tfrecord_file)
  writer.close()

  batch_size = 2

  filename_queue = tf.train.string_input_producer([tfrecord_file]) 
  reader = tf.TFRecordReader() 
  _, serialized_example = reader.read(filename_queue) 

  img_features = tf.parse_single_example( 
                    serialized_example, 
                    features={ 
                        'label': tf.FixedLenFeature([], tf.int64), 
                        'h': tf.FixedLenFeature([], tf.int64),
                        'w': tf.FixedLenFeature([], tf.int64),
                        'c': tf.FixedLenFeature([], tf.int64),
                        'image': tf.FixedLenFeature([], tf.string), 
                        }) 

  h = tf.cast(img_features['h'], tf.int32)
  w = tf.cast(img_features['w'], tf.int32)
  c = tf.cast(img_features['c'], tf.int32)

  image = tf.decode_raw(img_features['image'], tf.uint8) 
  image = tf.reshape(image, [h, w, c])

  label = tf.cast(img_features['label'],tf.int32) 
  label = tf.reshape(label, [1])

 # image = tf.image.resize_images(image, (500,500))
  #image, label = tf.train.batch([image, label], batch_size= batch_size) 


  with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    image, label=sess.run([image, label])
    coord.request_stop()
    coord.join(threads)

    print(label)

    plt.figure()
    plt.imshow(image)
    plt.show()


if __name__ == '__main__':
  main()

全部存入一个TFrecords文件,然后按照batch_size读取,注意需要将图片变成一样大才能按照batch_size读取。

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf


IMAGE_PATH = 'test/'
tfrecord_file = IMAGE_PATH + 'test.tfrecord'
writer = tf.python_io.TFRecordWriter(tfrecord_file)


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]))

def get_image_binary(filename):
  """ You can read in the image using tensorflow too, but it's a drag
    since you have to create graphs. It's much easier using Pillow and NumPy
  """
  image = Image.open(filename)
  image = np.asarray(image, np.uint8)
  shape = np.array(image.shape, np.int32)
  return shape, image.tobytes() # convert image to raw data bytes in the array.

def write_to_tfrecord(label, shape, binary_image, tfrecord_file):
  """ This example is to write a sample to TFRecord file. If you want to write
  more samples, just use a loop.
  """
  # write label, shape, and image content to the TFRecord file
  example = tf.train.Example(features=tf.train.Features(feature={
        'label': _int64_feature(label),
        'h': _int64_feature(shape[0]),
        'w': _int64_feature(shape[1]),
        'c': _int64_feature(shape[2]),
        'image': _bytes_feature(binary_image)
        }))
  writer.write(example.SerializeToString())


def write_tfrecord(label, image_file, tfrecord_file):
  shape, binary_image = get_image_binary(image_file)
  write_to_tfrecord(label, shape, binary_image, tfrecord_file)
  # print(shape)



def main():
  # assume the image has the label Chihuahua, which corresponds to class number 1
  label = [1,2]
  image_files = [IMAGE_PATH + 'a.jpg', IMAGE_PATH + 'b.jpg']

  for i in range(2):
    write_tfrecord(label[i], image_files[i], tfrecord_file)
  writer.close()

  batch_size = 2

  filename_queue = tf.train.string_input_producer([tfrecord_file]) 
  reader = tf.TFRecordReader() 
  _, serialized_example = reader.read(filename_queue) 

  img_features = tf.parse_single_example( 
                    serialized_example, 
                    features={ 
                        'label': tf.FixedLenFeature([], tf.int64), 
                        'h': tf.FixedLenFeature([], tf.int64),
                        'w': tf.FixedLenFeature([], tf.int64),
                        'c': tf.FixedLenFeature([], tf.int64),
                        'image': tf.FixedLenFeature([], tf.string), 
                        }) 

  h = tf.cast(img_features['h'], tf.int32)
  w = tf.cast(img_features['w'], tf.int32)
  c = tf.cast(img_features['c'], tf.int32)

  image = tf.decode_raw(img_features['image'], tf.uint8) 
  image = tf.reshape(image, [h, w, c])

  label = tf.cast(img_features['label'],tf.int32) 
  label = tf.reshape(label, [1])

  image = tf.image.resize_images(image, (224,224))
  image = tf.reshape(image, [224, 224, 3])
  image, label = tf.train.batch([image, label], batch_size= batch_size) 


  with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    image, label=sess.run([image, label])
    coord.request_stop()
    coord.join(threads)

    print(image.shape)
    print(label)

    plt.figure()
    plt.imshow(image[0,:,:,0])
    plt.show()

    plt.figure()
    plt.imshow(image[0,:,:,1])
    plt.show()

    image1 = image[0,:,:,:]
    print(image1.shape)
    print(image1.dtype)
    im = Image.fromarray(np.uint8(image1)) #参考numpy和图片的互转:http://blog.csdn.net/zywvvd/article/details/72810360
    im.show()

if __name__ == '__main__':
  main()

输出是

(2, 224, 224, 3)
[[1]
 [2]]

第一张图片的三种显示(略)

封装成函数:

# -*- coding: utf-8 -*-
"""
Created on Fri Sep 8 14:38:15 2017

@author: wayne


"""


'''
本文参考了以下代码,在多个不同大小图片存取方面做了重新开发:
https://github.com/chiphuyen/stanford-tensorflow-tutorials/blob/master/examples/09_tfrecord_example.py
http://blog.csdn.net/hjxu2016/article/details/76165559
https://stackoverflow.com/questions/41921746/tensorflow-varlenfeature-vs-fixedlenfeature
https://github.com/tensorflow/tensorflow/issues/10492

后续:
-存入多个TFrecords文件的例子见
http://blog.csdn.net/xierhacker/article/details/72357651
-如何作shuffle和数据增强
string_input_producer (需要理解tf的数据流,标签队列的工作方式等等)
http://blog.csdn.net/liuchonge/article/details/73649251
'''

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf


IMAGE_PATH = 'test/'
tfrecord_file = IMAGE_PATH + 'test.tfrecord'
writer = tf.python_io.TFRecordWriter(tfrecord_file)


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]))

def get_image_binary(filename):
  """ You can read in the image using tensorflow too, but it's a drag
    since you have to create graphs. It's much easier using Pillow and NumPy
  """
  image = Image.open(filename)
  image = np.asarray(image, np.uint8)
  shape = np.array(image.shape, np.int32)
  return shape, image.tobytes() # convert image to raw data bytes in the array.

def write_to_tfrecord(label, shape, binary_image, tfrecord_file):
  """ This example is to write a sample to TFRecord file. If you want to write
  more samples, just use a loop.
  """
  # write label, shape, and image content to the TFRecord file
  example = tf.train.Example(features=tf.train.Features(feature={
        'label': _int64_feature(label),
        'h': _int64_feature(shape[0]),
        'w': _int64_feature(shape[1]),
        'c': _int64_feature(shape[2]),
        'image': _bytes_feature(binary_image)
        }))
  writer.write(example.SerializeToString())


def write_tfrecord(label, image_file, tfrecord_file):
  shape, binary_image = get_image_binary(image_file)
  write_to_tfrecord(label, shape, binary_image, tfrecord_file)


def read_and_decode(tfrecords_file, batch_size): 
  '''''read and decode tfrecord file, generate (image, label) batches 
  Args: 
    tfrecords_file: the directory of tfrecord file 
    batch_size: number of images in each batch 
  Returns: 
    image: 4D tensor - [batch_size, width, height, channel] 
    label: 1D tensor - [batch_size] 
  ''' 
  # make an input queue from the tfrecord file 

  filename_queue = tf.train.string_input_producer([tfrecord_file]) 
  reader = tf.TFRecordReader() 
  _, serialized_example = reader.read(filename_queue) 

  img_features = tf.parse_single_example( 
                    serialized_example, 
                    features={ 
                        'label': tf.FixedLenFeature([], tf.int64), 
                        'h': tf.FixedLenFeature([], tf.int64),
                        'w': tf.FixedLenFeature([], tf.int64),
                        'c': tf.FixedLenFeature([], tf.int64),
                        'image': tf.FixedLenFeature([], tf.string), 
                        }) 

  h = tf.cast(img_features['h'], tf.int32)
  w = tf.cast(img_features['w'], tf.int32)
  c = tf.cast(img_features['c'], tf.int32)

  image = tf.decode_raw(img_features['image'], tf.uint8) 
  image = tf.reshape(image, [h, w, c])

  label = tf.cast(img_features['label'],tf.int32) 
  label = tf.reshape(label, [1])

  ########################################################## 
  # you can put data augmentation here  
#  distorted_image = tf.random_crop(images, [530, 530, img_channel])
#  distorted_image = tf.image.random_flip_left_right(distorted_image)
#  distorted_image = tf.image.random_brightness(distorted_image, max_delta=63)
#  distorted_image = tf.image.random_contrast(distorted_image, lower=0.2, upper=1.8)
#  distorted_image = tf.image.resize_images(distorted_image, (imagesize,imagesize))
#  float_image = tf.image.per_image_standardization(distorted_image)

  image = tf.image.resize_images(image, (224,224))
  image = tf.reshape(image, [224, 224, 3])
  #image, label = tf.train.batch([image, label], batch_size= batch_size) 

  image_batch, label_batch = tf.train.batch([image, label], 
                        batch_size= batch_size, 
                        num_threads= 64,  
                        capacity = 2000) 
  return image_batch, tf.reshape(label_batch, [batch_size]) 

def read_tfrecord2(tfrecord_file, batch_size):
  train_batch, train_label_batch = read_and_decode(tfrecord_file, batch_size)

  with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    train_batch, train_label_batch = sess.run([train_batch, train_label_batch])
    coord.request_stop()
    coord.join(threads)
  return train_batch, train_label_batch


def main():
  # assume the image has the label Chihuahua, which corresponds to class number 1
  label = [1,2]
  image_files = [IMAGE_PATH + 'a.jpg', IMAGE_PATH + 'b.jpg']

  for i in range(2):
    write_tfrecord(label[i], image_files[i], tfrecord_file)
  writer.close()

  batch_size = 2
  # read_tfrecord(tfrecord_file) # 读取一个图
  train_batch, train_label_batch = read_tfrecord2(tfrecord_file, batch_size)

  print(train_batch.shape)
  print(train_label_batch)

  plt.figure()
  plt.imshow(train_batch[0,:,:,0])
  plt.show()

  plt.figure()
  plt.imshow(train_batch[0,:,:,1])
  plt.show()

  train_batch1 = train_batch[0,:,:,:]
  print(train_batch.shape)
  print(train_batch1.dtype)
  im = Image.fromarray(np.uint8(train_batch1)) #参考numpy和图片的互转:http://blog.csdn.net/zywvvd/article/details/72810360
  im.show()

if __name__ == '__main__':
  main()

以上这篇TensorFLow 不同大小图片的TFrecords存取实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • Photoshop古装美女图片转为工笔画效果制作教程

    今天小编在这里就来给各位Photoshop的这一款软件的使用者们来说说把古装美女图片转为细腻的工笔画效果的制作教程,各位想知道方法的使用者们,那么下面就快来跟着小编一...2016-09-14
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮

    jquery左右滚动焦点图banner图片鼠标经过显示上下页按钮...2013-10-13
  • 利用JS实现点击按钮后图片自动切换的简单方法

    下面小编就为大家带来一篇利用JS实现点击按钮后图片自动切换的简单方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-10-25
  • Photoshop枪战电影海报图片制作教程

    Photoshop的这一款软件小编相信很多的人都已经是使用过了吧,那么今天小编在这里就给大家带来了用Photoshop软件制作枪战电影海报的教程,想知道制作步骤的玩家们,那么下面...2016-09-14
  • js实现上传图片及时预览

    这篇文章主要为大家详细介绍了js实现上传图片及时预览的相关资料,具有一定的参考价值,感兴趣的朋友可以参考一下...2016-05-09
  • python opencv通过4坐标剪裁图片

    图片剪裁是常用的方法,那么如何通过4坐标剪裁图片,本文就详细的来介绍一下,感兴趣的小伙伴们可以参考一下...2021-06-04
  • 使用PHP下载CSS文件中的图片的代码

    共享一段使用PHP下载CSS文件中的图片的代码 复制代码 代码如下: <?php //note 设置PHP超时时间 set_time_limit(0); //note 取得样式文件内容 $styleFileContent = file_get_contents('images/style.css'); //not...2013-10-04
  • PHP swfupload图片上传的实例代码

    PHP代码如下:复制代码 代码如下:if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) { $upload_file = $_FILES['Filedata']; $fil...2013-10-04
  • 微信小程序如何获取图片宽度与高度

    这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • C#中图片旋转和翻转(RotateFlipType)用法分析

    这篇文章主要介绍了C#中图片旋转和翻转(RotateFlipType)用法,实例分析了C#图片旋转及翻转Image.RotateFlip方法属性的常用设置技巧,需要的朋友可以参考下...2020-06-25
  • ps怎么制作图片阴影效果

    ps软件是现在很多人比较喜欢的,有着非常不错的使用效果,这次文章就给大家介绍下ps怎么制作图片阴影效果,还不知道制作方法的赶紧来看看。 ps图片阴影效果怎么做方法/...2017-07-06
  • OpenCV如何去除图片中的阴影的实现

    这篇文章主要介绍了OpenCV如何去除图片中的阴影的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-29
  • C#将图片和字节流互相转换并显示到页面上

    本文主要介绍用C#实现图片转换成字节流,字节流转换成图片,并根据图片路径返回图片的字节流,有需要的朋友可以参考下...2020-06-25
  • JavaScript 如何禁止用户保存图片

    这篇文章主要介绍了JavaScript 如何禁止用户保存图片,帮助大家完成需求,更好的理解和使用JavaScript,感兴趣的朋友可以了解下...2020-11-19
  • php上传图片学习笔记与心得

    我们在php中上传文件就必须使用#_FILE变量了,这个自动全局变量 $_FILES 从 PHP 4.1.0 版本开始被支持。在这之前,从 4.0.0 版本开始,PHP 支持 $HTTP_POST_FILES 数组。这...2016-11-25
  • SwiftUI图片缩放、拼图等处理教程

    SwiftUI是一种使用Swift语言在苹果设备上构建用户界面的创新且简单的方式,下面这篇文章主要给大家介绍了关于SwiftUI图片缩放、拼图等处理的相关资料,需要的朋友可以参考下...2021-08-23