title: Tensorflow: Extracting image and label from TFRecords file
body: <p>I have a TFRecords file which contains images with their labels, name, size, etc. My goal is to extract the label and the image as a numpy array.</p>
  
  <p>I do the following to load the file:</p>
  
  <pre><code>def extract_fn(data_record):
      features = {
          # Extract features using the keys set during creation
          "image/class/label":    tf.FixedLenFeature([], tf.int64),
          "image/encoded":        tf.VarLenFeature(tf.string),
      }
      sample = tf.parse_single_example(data_record, features)
      #sample = tf.cast(sample["image/encoded"], tf.float32)
      return sample
  
  filename = "path\train-00-of-10"
  dataset = tf.data.TFRecordDataset(filename)
  dataset = dataset.map(extract_fn)
  iterator = dataset.make_one_shot_iterator()
  next_element = iterator.get_next()
  
  with tf.Session() as sess:
      while True:
          data_record = sess.run(next_element)
          print(data_record)
  </code></pre>
  
  <p>The image is saved as a string. How can I convert the image to <code>float32</code>? I tried <code>sample = tf.cast(sample["image/encoded"], tf.float32)</code> which does not work. I want <code>data_record</code> to be a list containing the image as a numpy-array and the label as a <code>np.int32</code> number. How can I do that?</p>
  
  <p>Right now <code>data_record</code> looks like this:</p>
  
  <pre><code>{'image/encoded': SparseTensorValue(indices=array([[0]]), values=array([b'\xff\xd8\ ... 8G\xff\xd9'], dtype=object), dense_shape=array([1])), 'image/class/label': 394}
  </code></pre>
  
  <p>I have no idea how I can work with that. I would appreciate any help</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>If I print <code>sample</code> and <code>sample['image/encoded']</code> in <code>extract_fn()</code> I get the following:</p>
  
  <p><code>print(sample) = 
  {'image/encoded': &lt;tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x7fe41ec15978&gt;, 'image/class/label': &lt;tf.Tensor 'ParseSingleExample/ParseSingleExample:3' shape=() dtype=int64&gt;}</code></p>
  
  <p><code>print(sample['image/encoded'] = 
  SparseTensor(indices=Tensor("ParseSingleExample/ParseSingleExample:0", shape=(?, 1), dtype=int64), values=Tensor("ParseSingleExample/ParseSingleExample:1", shape=(?,), dtype=string), dense_shape=Tensor("ParseSingleExample/ParseSingleExample:2", shape=(1,), dtype=int64))</code></p>
  
  <p>It seems that the image is a sparse tensor and <code>tf.image.decode_image</code> throws an error. What is the right way to extract the image as an <code>tf.float32</code> tensor?</p>