Python 使用Tensorflow'序列化可变数量的二进制实例掩码;TFS记录格式

Python 使用Tensorflow'序列化可变数量的二进制实例掩码;TFS记录格式,python,tensorflow,tfrecord,Python,Tensorflow,Tfrecord,对于MS Coco 2014数据集,每个图像都有数量可变的边界框和相应的二进制实例遮罩,这些遮罩可以从注释文件中给出的实例多边形中获得。我使用pycocotools(特别是coco.py文件)实现了这一点。现在我希望使用Tensorflow的tfrecords格式序列化图像信息。在读取python dict的注释(按每个图像id编制索引)后,我能够序列化不同数量的边界框,如: x_min_values = [] x_max_values = [] y_min_values = [] y_max_

对于MS Coco 2014数据集,每个图像都有数量可变的边界框和相应的二进制实例遮罩,这些遮罩可以从注释文件中给出的实例多边形中获得。我使用pycocotools(特别是coco.py文件)实现了这一点。现在我希望使用Tensorflow的tfrecords格式序列化图像信息。在读取python dict的注释(按每个图像id编制索引)后,我能够序列化不同数量的边界框,如:

x_min_values = []
x_max_values = []
y_min_values = []
y_max_values = []
for bb in bounding_boxes:
    x_min_values.append(int(bb[0]))
    y_min_values.append(int(bb[1]))
    x_max_values.append(int(bb[2]))
    y_max_values.append(int(bb[3]))
然后,为了在
tf.train.Example
中使用我的特性dict,我将每个列表转换为int64特性列表,如下所示:

def _int64_feature_list(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) 

但现在的问题是,由于实例掩码是二维的,我不确定应该使用什么策略来序列化它们。如果只有一个掩码,就像在分割掩码中一样,那么我可以简单地展平数组,并编写一个64位的特征列表,然后在反序列化时使用图像高度和宽度来重塑数组,但对于数量可变的掩码,我不能这样做。任何见解都值得赞赏。

需要使用FixedLenSequenceFeature,如下所述:


两个图像的示例,每个图像具有3个和2个边界框

bounding_boxes = []
bounding_boxes.append(np.random.randint(low=0, high=2000,size=(3, 4)))  
bounding_boxes.append(np.random.randint(low=0, high=2000,size=(2, 4)))  
for i, box in enumerate(bounding_boxes):
    print({i},box)
输出:

{0}[[1806 1172 1919 1547]
[14781654481689]
[1315151516541586]]

{1} [[601 1473 1670 756]
[1791 993 1049 1793]]

#Write tfrecord
def _int64_feature(list_of_ints):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=list_of_ints))

out_path = './test.tfrec'
with tf.io.TFRecordWriter(out_path) as out:
    for box in bounding_boxes:            
        
        example = tf.train.Example(features=tf.train.Features(feature={
            'boxes': _int64_feature(np.array(box).flatten().tolist()),
            }))
        out.write(example.SerializeToString())
检查书面记录:

ds = tf.data.TFRecordDataset(out_path)

for i, data in enumerate(ds):
    process_each = {
        'boxes': tf.io.FixedLenSequenceFeature([], dtype=tf.int64, allow_missing=True),            
    }
    samples = tf.io.parse_example(data, process_each)
    print(i, samples['boxes'].numpy().reshape(-1, 4))
    
输出:

0[[18061172 1919191547]
[14781654481689]
[1315151516541586]]
1[[601 1473 1670 756]

[1791 993 1049 1793]

最初的问题是关于实例掩码的。这是一个很好的答案,用于序列化边界框的变量数,我将把它合并到我的代码中。谢谢你的帮助。
#Write tfrecord
def _int64_feature(list_of_ints):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=list_of_ints))

out_path = './test.tfrec'
with tf.io.TFRecordWriter(out_path) as out:
    for box in bounding_boxes:            
        
        example = tf.train.Example(features=tf.train.Features(feature={
            'boxes': _int64_feature(np.array(box).flatten().tolist()),
            }))
        out.write(example.SerializeToString())