优化程序import os import xml.etree.ElementTree as ET def convert_txt_to_xml(txt_file, xml_file): # 创建XML根节点 root = ET.Element("annotation") # 读取txt文件内容 with open(txt_file, "r") as f: lines = f.readlines() # 创建子节点 folder = ET.SubElement(root, "folder") folder.text = "labelimg" filename = ET.SubElement(root, "filename") filename.text = os.path.splitext(os.path.basename(txt_file))[0] + ".jpg" # 循环处理每行数据 for line in lines: line = line.strip().split(" ") # 创建对象节点 object_node = ET.SubElement(root, "object") # 创建子节点 name = ET.SubElement(object_node, "name") name.text = line[0] pose = ET.SubElement(object_node, "pose") pose.text = "Unspecified" truncated = ET.SubElement(object_node, "truncated") truncated.text = "0" difficult = ET.SubElement(object_node, "difficult") difficult.text = "0" # 创建子节点(边界框) bndbox = ET.SubElement(object_node, "bndbox") xmin = ET.SubElement(bndbox, "xmin") xmin.text = line[1] ymin = ET.SubElement(bndbox, "ymin") ymin.text = line[2] xmax = ET.SubElement(bndbox, "xmax") xmax.text = line[3] ymax = ET.SubElement(bndbox, "ymax") ymax.text = line[4] # 创建XML树对象 tree = ET.ElementTree(root) # 写入XML文件 tree.write(xml_file) # 示例用法 txt_file = "txt/labels" xml_file = "txt/xml" convert_txt_to_xml(txt_file, xml_file) ,修改为对labels文件夹下的所有txt文件进行转换,转换后的xml文件并保存在xml文件夹下
时间: 2024-04-22 17:26:05 浏览: 210
你可以使用`os.listdir()`函数来获取指定路径下的所有文件,然后筛选出.txt文件进行转换。下面是优化后的代码示例:
```python
import os
import xml.etree.ElementTree as ET
def convert_txt_to_xml(txt_folder, xml_folder):
# 遍历txt文件夹下的所有txt文件
for txt_file in os.listdir(txt_folder):
if txt_file.endswith(".txt"):
# 构造txt和对应的xml文件路径
txt_path = os.path.join(txt_folder, txt_file)
xml_file = os.path.splitext(txt_file)[0] + ".xml"
xml_path = os.path.join(xml_folder, xml_file)
# 创建XML根节点
root = ET.Element("annotation")
# 读取txt文件内容
with open(txt_path, "r") as f:
lines = f.readlines()
# 创建子节点
folder = ET.SubElement(root, "folder")
folder.text = "labelimg"
filename = ET.SubElement(root, "filename")
filename.text = os.path.splitext(os.path.basename(txt_file))[0] + ".jpg"
# 循环处理每行数据
for line in lines:
line = line.strip().split(" ")
# 创建对象节点
object_node = ET.SubElement(root, "object")
# 创建子节点
name = ET.SubElement(object_node, "name")
name.text = line[0]
pose = ET.SubElement(object_node, "pose")
pose.text = "Unspecified"
truncated = ET.SubElement(object_node, "truncated")
truncated.text = "0"
difficult = ET.SubElement(object_node, "difficult")
difficult.text = "0"
# 创建子节点(边界框)
bndbox = ET.SubElement(object_node, "bndbox")
xmin = ET.SubElement(bndbox, "xmin")
xmin.text = line[1]
ymin = ET.SubElement(bndbox, "ymin")
ymin.text = line[2]
xmax = ET.SubElement(bndbox, "xmax")
xmax.text = line[3]
ymax = ET.SubElement(bndbox, "ymax")
ymax.text = line[4]
# 创建XML树对象
tree = ET.ElementTree(root)
# 写入XML文件
tree.write(xml_path)
```
示例用法:
```python
txt_folder = "txt/labels"
xml_folder = "txt/xml"
convert_txt_to_xml(txt_folder, xml_folder)
```
这样,代码会遍历`txt/labels`文件夹下的所有.txt文件,并将转换后的XML文件保存在`txt/xml`文件夹下,文件名与对应的txt文件相同但扩展名改为.xml。
阅读全文