未正确读取Tensorflow tfrecord

时间:2018-01-16 01:49:35

标签: python tensorflow tfrecord

我正在尝试使用Tensorflow在我自己的分段数据集上训练CNN。根据我的研究,tfRecords似乎是最好的方式。我已经想出如何写入和读取tfRecord数据库,但我尝试在Tensorflow图中成功读取它。以下是从我的数据库中成功重建图像和地面实况的片段:

data_path = 'Training/train.tfrecords'  # address to save the hdf5 file

record_iterator = tf.python_io.tf_record_iterator(path=data_path)
reconstructed_images = []
reconstructed_groundtruths = []
count = 0
for string_record in record_iterator:
  example = tf.train.Example()
  example.ParseFromString(string_record)
  height = int(example.features.feature['height']
                             .int64_list
                             .value[0])

  width = int(example.features.feature['width']
                            .int64_list
                            .value[0])

  gt_string = (example.features.feature['train/groundTruth']
                              .bytes_list
                              .value[0])

  image_string = (example.features.feature['train/image']
                            .bytes_list
                            .value[0])

  img_1d = np.fromstring(image_string, dtype=np.uint8)
  reconstructed_img = img_1d.reshape((height, width))
  gt_1d = np.fromstring(gt_string, dtype=np.uint8)
  reconstructed_gt = gt_1d.reshape((height, width))

  reconstructed_images.append(reconstructed_img)
  reconstructed_groundtruths.append(reconstructed_gt)
  count += 1

这段代码成功地为我提供了数据库中图像和地面实况标签的numpy数组列表。现在,为了尝试实际训练某些东西,我正在使用您可以找到的here的MNIST示例。

我已使用以下内容替换了解码功能:

def decode(serialized_example):

  features = tf.parse_single_example(
    serialized_example,
    # Defaults are not specified since both keys are required.
    features={
      'height': tf.FixedLenFeature([1],tf.int64),
      'width': tf.FixedLenFeature([1],tf.int64),
      'train/image': tf.FixedLenFeature([], tf.string),
      'train/groundTruth': tf.FixedLenFeature([], tf.string),
    })


  height = tf.cast(features['height'], tf.int64)
  width = tf.cast(features['width'], tf.int64)
  image = tf.decode_raw(features['train/image'], tf.uint8)
  image.set_shape((height,width))
  gt = tf.decode_raw(features['train/groundTruth'], tf.uint8)
  gt.set_shape((height,width))


  return image, gt

当我运行它时,有多个问题表明代码只是无法读取数据库。如上所述,我将在解析height的行上收到错误,其中说明了

  

int()参数必须是字符串,类似字节的对象或数字,而不是   '张量'

如果我暂时将heightwidth设置为文字,我会在图像解析行上出现错误

  

形状(?,)和(512,512)不兼容

很明显,这意味着图像没有从数据库中正确读取,但我完全不知道为什么或如何解决它。有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

我真的找到了解决方案。显然,

image.set_shape((height,width)) 

应该是

image = tf.reshape(image,(height,width,1))

与gt类似。我不知道为什么我关注的Tensorflow教程使用了set_shape ...我能猜到的是它适用于1d但不适用于2d或更多?我现在可以看到它也不是一个张量函数,因此它不能使用像高度这样的图形相关变量,但仅凭这一点并不能解释为什么当我用全局替换(高度,宽度)时它不起作用常量。如果有人知道,我们将不胜感激。