【问题标题】:How can I convert TFRecords into numpy arrays?如何将 TFRecords 转换为 numpy 数组?
【发布时间】:2016-07-01 19:32:37
【问题描述】:

主要思想是将 TFRecords 转换为 numpy 数组。假设 TFRecord 存储图像。具体来说:

  1. 读取 TFRecord 文件并将每个图像转换为 numpy 数组。
  2. 将图片写入1.jpg、2.jpg等格式
  3. 同时,将文件名和标签写入文本文件,如下所示:
    1.jpg 2
    2.jpg 4
    3.jpg 5
    

我目前使用以下代码:

import tensorflow as tf
import os

def read_and_decode(filename_queue):
  reader = tf.TFRecordReader()
  _, serialized_example = reader.read(filename_queue)
  features = tf.parse_single_example(
      serialized_example,
      # Defaults are not specified since both keys are required.
      features={
          'image_raw': tf.FixedLenFeature([], tf.string),
          'label': tf.FixedLenFeature([], tf.int64),
          'height': tf.FixedLenFeature([], tf.int64),
          'width': tf.FixedLenFeature([], tf.int64),
          'depth': tf.FixedLenFeature([], tf.int64)
      })
  image = tf.decode_raw(features['image_raw'], tf.uint8)
  label = tf.cast(features['label'], tf.int32)
  height = tf.cast(features['height'], tf.int32)
  width = tf.cast(features['width'], tf.int32)
  depth = tf.cast(features['depth'], tf.int32)
  return image, label, height, width, depth

with tf.Session() as sess:
  filename_queue = tf.train.string_input_producer(["../data/svhn/svhn_train.tfrecords"])
  image, label, height, width, depth = read_and_decode(filename_queue)
  image = tf.reshape(image, tf.pack([height, width, 3]))
  image.set_shape([32,32,3])
  init_op = tf.initialize_all_variables()
  sess.run(init_op)
  print (image.eval())

我只是想为初学者获取至少一张图片。当我运行它时,代码只是卡住了。

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    糟糕,我犯了一个愚蠢的错误。我使用了 string_input_producer 但忘记运行 queue_runners。

    with tf.Session() as sess:
      filename_queue = tf.train.string_input_producer(["../data/svhn/svhn_train.tfrecords"])
      image, label, height, width, depth = read_and_decode(filename_queue)
      image = tf.reshape(image, tf.pack([height, width, 3]))
      image.set_shape([32,32,3])
      init_op = tf.initialize_all_variables()
      sess.run(init_op)
      coord = tf.train.Coordinator()
      threads = tf.train.start_queue_runners(coord=coord)
      for i in range(1000):
        example, l = sess.run([image, label])
        print (example,l)
      coord.request_stop()
      coord.join(threads)
    

    【讨论】:

    • 希望我能多点赞。我到处找这个!
    • 非常感谢!堆栈溢出应该添加一个捐赠给贡献者按钮
    • 请注意,自 tf 1.0 起,tf.pack() 更改为 tf.stack()
    猜你喜欢
    • 2021-12-18
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 2021-12-14
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多