xml转txt,划分数据集代码

14 篇文章 0 订阅
14 篇文章 0 订阅

adgjh

xml转txt的代码 01_xml_to_txt

import xml.etree.ElementTree as ET
import os

from PIL import Image


def convert(size, box):
    x_center = (box[0] + box[1]) / 2.0
    y_center = (box[2] + box[3]) / 2.0
    x = x_center / size[0]
    y = y_center / size[1]
    w = (box[1] - box[0]) / size[0]
    h = (box[3] - box[2]) / size[1]
    return (x, y, w, h)

def convert_format(xml_files_path, save_txt_files_path, classes):
    if not os.path.exists(save_txt_files_path):
        os.makedirs(save_txt_files_path)
    xml_files = os.listdir(xml_files_path)
    # print(xml_files)
    for xml_name in xml_files:
        # print(xml_name)
        xml_file = os.path.join(xml_files_path, xml_name)
        out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
        out_txt_f = open(out_txt_path, 'w')
        tree = ET.parse(xml_file)
        root = tree.getroot()
        size = root.find('size')
        if size is None:
            w, h = get_imgwh(xml_file)
        else:
            w = int(size.find('width').text)
            h = int(size.find('height').text)
            if w == 0 or h == 0:
                w, h = get_imgwh(xml_file)

        for obj in root.iter('object'):
            difficult = obj.find('difficult').text
            cls = obj.find('name').text
            if cls not in classes or int(difficult) == 1:
                continue
            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                 float(xmlbox.find('ymax').text))
            # b=(xmin, xmax, ymin, ymax)
            # print(w, h, b)
            try:
                bb = convert((w, h), b)
            except:
                print(f"convert转换异常: {xml_file}")
            out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')

def get_imgwh(xml_file):
    img_path = xml_file.replace("Annotations", "JPEGImages").replace(".xml", image_suffix)
    img_pil = Image.open(img_path)
    w, h = img_pil.size
    return w, h

if __name__ == "__main__":
    """
    说明:
    BASE_PATH: 数据集标签目录的上一级路径
    注意数据集里面的标签文件: 目录名是 Annotations
    保存为txt的标签目录名是:  labels
    """
    BASE_PATH = r"./VOC2007"
    image_suffix = ".jpg"
    # 需要转换的类别,需要一一对应
    classes = ['face', 'face_mask']
    # 2、voc格式的xml标签文件路径
    xml_files = os.path.join(BASE_PATH, "Annotations")
    # 3、转化为yolo格式的txt标签文件存储路径
    save_txt_files = os.path.join(BASE_PATH, "labels")
    convert_format(xml_files, save_txt_files, classes)

 划分数据集的代码

"""
1.将图片和标注数据按比例切分为 训练集和测试集
2.原图片的目录名是:  JPEGImages
3.对应的txt标签是之前转换的labels
4.训练集、测试集、验证集 路径和VOC2007路径保持一致
"""
import shutil
import random
import os

BASE_PATH = r"E:\python_code\pythonProject2\Covert_txt"
# 数据集路径
image_original_path = os.path.join(BASE_PATH, "VOC2007/JPEGImages/")
label_original_path = os.path.join(BASE_PATH, "VOC2007/labels/")

# 训练集路径
train_image_path = os.path.join(BASE_PATH, "train/images/")
train_label_path = os.path.join(BASE_PATH, "train/labels/")

# 验证集路径
val_image_path = os.path.join(BASE_PATH, "val/images/")
val_label_path = os.path.join(BASE_PATH, "val/labels/")
# 测试集路径
test_image_path = os.path.join(BASE_PATH, "test/images/")
test_label_path = os.path.join(BASE_PATH, "test/labels/")

# 数据集划分比例,训练集75%,验证集15%,测试集15%,按需修改
train_percent = 0.8
val_percent = 0.2
test_percent = 0


# 检查文件夹是否存在
def mkdir():
	if not os.path.exists(train_image_path) and train_percent > 0:
		os.makedirs(train_image_path)
	if not os.path.exists(train_label_path) and train_percent > 0:
		os.makedirs(train_label_path)

	if not os.path.exists(val_image_path) and val_percent > 0:
		os.makedirs(val_image_path)
	if not os.path.exists(val_label_path) and val_percent > 0:
		os.makedirs(val_label_path)

	if not os.path.exists(test_image_path) and test_percent > 0:
		os.makedirs(test_image_path)
	if not os.path.exists(test_label_path) and test_percent > 0:
		os.makedirs(test_label_path)


def main():
	mkdir()
	total_txt = os.listdir(label_original_path)
	num_txt = len(total_txt)
	list_all_txt = range(num_txt)  # 范围 range(0, num)
	# 0.75 * num_txt
	num_train = int(num_txt * train_percent)
	# 0.15 * num_txt
	# 如果测试集test_percent==0, 直接使用总数量减去训练集的数量
	if test_percent == 0:
		num_val = num_txt - num_train
	else:
		num_val = int(num_txt * val_percent)
	num_test = num_txt - num_train - num_val

	train = random.sample(list_all_txt, num_train)
	# 在全部数据集中取出train
	val_test = [i for i in list_all_txt if not i in train]
	# 再从val_test取出num_val个元素,val_test剩下的元素就是test
	val = random.sample(val_test, num_val)
	print("训练集数目:{}, 验证集数目:{},测试集数目:{}".format(len(train), len(val), len(val_test) - len(val)))
	for i in list_all_txt:
		name = total_txt[i][:-4]

		srcImage = image_original_path + name + '.jpg'
		srcLabel = label_original_path + name + '.txt'

		if i in train:
			dst_train_Image = train_image_path + name + '.jpg'
			dst_train_Label = train_label_path + name + '.txt'
			shutil.copyfile(srcImage, dst_train_Image)
			shutil.copyfile(srcLabel, dst_train_Label)
		elif i in val:
			dst_val_Image = val_image_path + name + '.jpg'
			dst_val_Label = val_label_path + name + '.txt'
			shutil.copyfile(srcImage, dst_val_Image)
			shutil.copyfile(srcLabel, dst_val_Label)
		else:
			dst_test_Image = test_image_path + name + '.jpg'
			dst_test_Label = test_label_path + name + '.txt'
			shutil.copyfile(srcImage, dst_test_Image)
			shutil.copyfile(srcLabel, dst_test_Label)


if __name__ == '__main__':
	main()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西柚与蓝莓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值