在python中创建一个.py文件,然后把文件路径填为自己的就行
1.xml转txt
import os
import xml.etree.ElementTree as ET
# YOLO 格式转换函数
def convert_xml_to_yolo(xml_file, output_file, image_width, image_height):
# 解析 XML 文件
tree = ET.parse(xml_file)
root = tree.getroot()
with open(output_file, 'w') as f:
for obj in root.findall("object"):
# 获取类别名称
label_name = obj.find("name").text
# 根据类别名称映射到类别 ID
label_to_name = {
"Alligator crack": 0,
"Longitudinal crack": 1,
"Oblique crack": 2,
"Repair": 3,
"Transverse crack": 4
}
label_id = label_to_name.get(label_name, -1)
if label_id == -1:
print(f"未知类别: {label_name}")
continue
# 获取边界框信息
bndbox = obj.find("bndbox")
x_min = float(bndbox.find("xmin").text)
y_min = float(bndbox.find("ymin").text)
x_max = float(bndbox.find("xmax").text)
y_max = float(bndbox.find("ymax").text)
# 转换为 YOLO 格式
x_center = (x_min + x_max) / 2 / image_width
y_center = (y_min + y_max) / 2 / image_height
width = (x_max - x_min) / image_width
height = (y_max - y_min) / image_height
# 写入 .txt 文件
f.write(f"{label_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")
# 批量转换函数
def convert_xml_folder_to_yolo(input_folder, output_folder, image_width, image_height):
# 确保输出文件夹存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 遍历 XML 文件夹中的所有文件
for filename in os.listdir(input_folder):
if filename.endswith(".xml"):
xml_file_path = os.path.join(input_folder, filename)
txt_file_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}.txt")
# 转换为 YOLO 格式
convert_xml_to_yolo(xml_file_path, txt_file_path, image_width, image_height)
print(f"转换完成: {xml_file_path} -> {txt_file_path}")
# 主函数
if __name__ == "__main__":
# 输入文件夹路径
input_folder = r"D:\labels\xml\test" # XML 文件夹路径
output_folder = r"D:\labels\test" # 输出 TXT 文件夹路径
image_width = 1024 # 图像宽度
image_height = 1024 # 图像高度
# 批量转换
convert_xml_folder_to_yolo(input_folder, output_folder, image_width, image_height)
2.json转.txt
import json
import os
# 标签类别和对应的 ID
label_to_id = {
"Alligator crack": 0,
"Longitudinal crack": 1,
"Oblique crack": 2,
"Repair": 3,
"Transverse crack": 4
}
def convert_to_yolo_format(json_file):
with open(json_file, 'r') as f:
data = json.load(f)
image_width = data["imageWidth"]
image_height = data["imageHeight"]
output_txt = []
for shape in data["shapes"]:
label = shape["label"]
points = shape["points"]
# 获取边界框的四个角坐标
x_min = min([point[0] for point in points])
x_max = max([point[0] for point in points])
y_min = min([point[1] for point in points])
y_max = max([point[1] for point in points])
# 计算中心点坐标和宽度/高度
x_center = (x_min + x_max) / 2
y_center = (y_min + y_max) / 2
width = x_max - x_min
height = y_max - y_min
# 将坐标归一化
x_center_norm = x_center / image_width
y_center_norm = y_center / image_height
width_norm = width / image_width
height_norm = height / image_height
# 获取标签 ID
label_id = label_to_id.get(label, -1)
# 存储转换后的结果
output_txt.append(f"{label_id} {x_center_norm} {y_center_norm} {width_norm} {height_norm}")
return output_txt
def save_yolo_labels(output_txt, output_file):
with open(output_file, 'w') as f:
for line in output_txt:
f.write(line + '\n')
# 输入文件夹路径
input_folder = r"D:\labels\test" # 请替换为你的文件夹路径
output_folder = r"D:\labels\txt版本\test" # 请替换为你想保存的txt文件夹路径
# 遍历文件夹中的所有 JSON 文件
for filename in os.listdir(input_folder):
if filename.endswith(".json"):
json_file_path = os.path.join(input_folder, filename)
# 为输出 txt 文件创建对应的路径
output_txt_file = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}.txt")
# 转换为 YOLO 格式
yolo_labels = convert_to_yolo_format(json_file_path)
# 保存到 txt 文件
save_yolo_labels(yolo_labels, output_txt_file)
print(f"YOLO 格式标签已保存到: {output_txt_file}")
使用上述代码即可转换为下列.txt标签格式啦