1

我正在尝试在 python 中应用代码以从每个 xml 文件中提取必要的信息并将它们写入 txt 文件。我成功执行了我的代码,但结果只显示一个文件。另外,我的代码看起来并不聪明,如果有人可以帮助我解决问题并给我一些修正,我会很高兴。

恐怕我是初学者,所以我可能有很多基本错误......

这是我的代码


from xml.etree import ElementTree as ET
import os

path = r'/Users/mo/Documents/annotations/xmls'
filenames = []

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue
    fullname = os.path.join(path,filename)
    filenames.append(fullname)

each_name = filename[:-4]

with open(each_name + '.txt', 'a') as f:

    for filename in filenames:
        tree = ET.parse(filename)
        root = tree.getroot()

        for object in root.findall('object'):
            categoryID = object.find('name').text

            for bnd_box in object.findall('bndbox'):
                Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
                Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
                width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
                height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
                Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'

    f.write(str(Detection_rows))

非常感谢

4

1 回答 1

0

试试这个(没有测试过

from xml.etree import ElementTree as ET
import os

path = r'/Users/mo/Documents/annotations/xmls'

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue
        
    fullname = os.path.join(path, filename)

    with open(fullname[:-4] + '.txt', 'a') as f:

        tree = ET.parse(fullname)
        root = tree.getroot()

        for object in root.findall('object'):
            categoryID = object.find('name').text

            for bnd_box in object.findall('bndbox'):
                Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
                Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
                width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
                height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
                Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'

        f.write(str(Detection_rows))

你的 for 循环应该在外部open并且你改变filenames了 for filename。另外,我删除了一个不必要的 for 循环。让我知道它是否可以为您解决问题。

于 2020-08-22T16:57:04.120 回答