将文本文件注释转换为xml文件

时间:2018-11-27 17:04:03

标签: python xml deep-learning

我已经为场景文本检测生成了大约7000张图像和地面真相。我想在文本框中进行训练。模型希望注释格式为xml格式,具体来说就是这样。< / p>

<?xml version="1.0" encoding="utf-8"?>
<annotation>
    <object>
        <difficult>1</difficult>
        <content>###</content>
        <name>text</name>
        <bndbox>
            <x1>261</x1>
            <y1>138</y1>
            <x2>284</x2>
            <y2>140</y2>
            <x3>279</x3>
            <y3>158</y3>
            <x4>260</x4>
            <y4>158</y4>
            <xmin>260</xmin>
            <ymin>138</ymin>
            <xmax>284</xmax>
            <ymax>158</ymax>
        </bndbox>
    </object>
    <object>
        <difficult>0</difficult>
        <content>HarbourFront</content>
        <name>text</name>
        <bndbox>
            <x1>288</x1>
            <y1>138</y1>
            <x2>417</x2>
            <y2>140</y2>
            <x3>416</x3>
            <y3>161</y3>
            <x4>290</x4>
            <y4>157</y4>
            <xmin>288</xmin>
            <ymin>138</ymin>
            <xmax>417</xmax>
            <ymax>161</ymax>
        </bndbox>
    </object>
    <object>
        <difficult>0</difficult>
        <content>CC22</content>
        <name>text</name>
<bndbox>

我大约有7000个文本,每个图像一个,示例文本文件内容如下

135,34,210,34,210,57,135,57,Tobii 224,34,321,34,321,57,224,57,TX300 335,34,388,34,388,63,335,63,Eye 400,34,517,34,517,57,400,57,Tracker 140,67,171,67,171,80,140,80,300 181,66,202,66,202,80,181,80,### 212,66,294,66,294,83,212,83,sampling 305,67,337,67,337,80,305,80,rate 140,85,171,85,171,99,140,99,and 180,85,251,85,251,99,180,99,freedom 259,85,275,85,275,99,259,99,### 282,87,373,87,373,99,282,99,movement

无论如何,我可以将这些文本文件内容转换为上面显示的xml格式吗? 任何建议都会真正有用。谢谢。

1 个答案:

答案 0 :(得分:0)

您可能只为每个xml元素使用一个模板,然后将属性列表粘贴到模板中。

例如

xml_substring_list = []

for txt_file_name in txt_file_names:

    with open(txt_file_name, 'r') as file_in:
        obj_attributes_string = file_in.readline().strip()
        obj_attributes_split = obj_attributes_string.split(',') //list of individual attribute strings

    new_xml_substring = """    <object>
        <difficult>{}</difficult>
        <content>{}</content>
        <name>{}</name>
        <bndbox>
            <x1>{}</x1>
            <y1>{}</y1>
            <x2>{}</x2>
            <y2>{}</y2>
            <x3>{}</x3>
            <y3>{}</y3>
            <x4>{}</x4>
            <y4>{}</y4>
            <xmin>{}</xmin>
            <ymin>{}</ymin>
            <xmax>{}</xmax>
            <ymax>{}</ymax>
        </bndbox>
    </object>""".format(*obj_attributes_split)

    xml_substring_list.append(new_xml_substring)
//Create full xml by concatenating substrings and adding wrapping xml string