Search code examples
tensorflowtfrecord

Getting TypeError: While Creating TFRecords for Image input


Creating TFrecords for Image input: as below

        char_ids_padded, char_ids_unpadded = encode_utf8_string(text)
        print("char_ids_padded:"+str(char_ids_padded))
        print("char_ids_unpadded:"+str(char_ids_unpadded))
        tf_example = tf.train.Example(features=tf.train.Features(feature={
            'image/format': _bytes_feature(b'png'),
            'image/encoded': _bytes_feature(image.tostring()),
            'image/class': _int64_feature(char_ids_padded),
            'image/unpadded_class': _int64_feature(char_ids_unpadded),
            'height': _int64_feature(image.shape[0]),
            'width': _int64_feature(image.shape[1]),
            'orig_width': _int64_feature(image.shape[1]/num_of_views),
            'image/text': _bytes_feature(text)
            }))


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

Output for char_ids_padded, char_ids_unpadded as below:

char_ids_padded:[47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

char_ids_unpadded:[47, 13, 16, 13, 16, 16, 16, 52]

Note: char_ids_padded is in list format with type int, Still while mapping with tf.train.Features, getting error as TypeError: [47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] has type "class 'list'", but expected one of: ("class 'int'",)


Solution

  • You're already passing a list to tf.train.Int64List, so you don't need to create a new list containing the argument of _int64_feature. That is, you should try changing

    tf.train.Int64List(value=[value])
    

    to

    tf.train.Int64List(value=value)
    

    in the _int64_feature function.

    When I run the following code, it works:

    def _int64_feature(value):
        return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
    
    char_ids_padded = [47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    tf_example = tf.train.Example(features=tf.train.Features(feature={
         'image/class': _int64_feature(char_ids_padded),
    }))