侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

技术  /  管理员 发布于 7年前   287

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

不多写了,直接贴代码。

from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfIMAGE_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 Imageimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfIMAGE_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.pyhttp://blog.csdn.net/hjxu2016/article/details/76165559https://stackoverflow.com/questions/41921746/tensorflow-varlenfeature-vs-fixedlenfeaturehttps://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 Imageimport numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfIMAGE_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_batchdef 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存取实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    使用TensorFlow对图像进行随机旋转的实现示例
    下一条:
    tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客