Serialize Variable Number of Binary Instance Masks ด้วยรูปแบบ tfrecord ของ Tensorflow

Nov 27 2020

สำหรับชุดข้อมูล MS Coco 2014 แต่ละรูปภาพจะมีจำนวนกล่องขอบเขตที่หลากหลายและมาสก์อินสแตนซ์ไบนารีที่สอดคล้องกันซึ่งสามารถหาได้จากรูปหลายเหลี่ยมอินสแตนซ์ที่ระบุในไฟล์หมายเหตุ ฉันทำได้โดยใช้ pycocotools (โดยเฉพาะไฟล์ coco.py) ตอนนี้ฉันต้องการจัดลำดับข้อมูลภาพโดยใช้รูปแบบ tfrecords ของ Tensorflow หลังจากอ่านคำอธิบายประกอบเป็น python dict ซึ่งจัดทำดัชนีโดยแต่ละรหัสรูปภาพฉันสามารถจัดลำดับหมายเลขตัวแปรของกล่องขอบเขตเช่น:

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ฉันฉันแปลงแต่ละรายการเป็นรายการคุณลักษณะ int64 เป็น:

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

แต่ตอนนี้ปัญหาคือเนื่องจากอินสแตนซ์มาสก์เป็นแบบ 2 มิติฉันไม่แน่ใจว่าควรใช้กลยุทธ์ใดในการทำให้เป็นอนุกรม หากมีเพียงรูปแบบเดียวเช่นเดียวกับในมาสก์การแบ่งส่วนฉันก็สามารถทำให้อาร์เรย์แบนเรียบและเขียนรายการคุณลักษณะ 64 บิตจากนั้นใช้ความสูงและความกว้างของรูปภาพเพื่อปรับรูปร่างอาร์เรย์ใหม่เมื่อแยกส่วนออก แต่ฉันทำไม่ได้ สำหรับจำนวนมาสก์ที่แปรผัน ข้อมูลเชิงลึกใด ๆ ที่ชื่นชม

คำตอบ

vijaym Dec 08 2020 at 03:24

จำเป็นต้องใช้FixedLenSequenceFeatureดังอธิบายด้านล่าง:


ตัวอย่างของภาพ 2 ภาพที่มีกล่องล้อมรอบ 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]
[1478 1654 498 1689]
[131515 1654 1586]]

{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())

ตรวจสอบ tfrecord ที่เขียน:

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 [[1806 1172 1919 1547]
[1478 1654 498 1689]
[131 515 1654 1586]]
1 [[601 1473 1670 756]
[1791 993 1049 1793]]