赞
踩
# coding:utf-8
import os
import random
import argparse
"""
根据label的所有xml划分训练,测试,验证集合
输入所有xml路径,输出三个txt(里面是图片名,每一行是一个图片)
"""
parser = argparse.ArgumentParser()
# xml文件的地址,根据自己的数据进行修改 xml一般存放在Annotations下
parser.add_argument('--xml_path', default='data/mydata/Annotations', type=str, help='input xml label path')
# 数据集的划分,地址选择自己数据下的ImageSets/Main
parser.add_argument('--txt_path', default='data/mydata/dataSet', type=str, help='output txt label path')
opt = parser.parse_args()
def split_data_indices(total_indices):
random.shuffle(total_indices)
total_samples = len(total_indices)
train_ratio, test_ratio = 0.7, 0.2
train_end = int(total_samples * train_ratio)
test_end = int(total_samples * (train_ratio + test_ratio))
train_indices = total_indices[:train_end]
test_indices = total_indices[train_end:test_end]
val_indices = total_indices[test_end:]
return train_indices, test_indices, val_indices
xmlfilepath = opt.xml_path
txtsavepath = opt.txt_path
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
os.makedirs(txtsavepath)
num = len(total_xml)
list_index = list(range(num))
train_indices, test_indices, val_indices = split_data_indices(list_index)
#'data/mydata/dataSet下创建划分数据集的图片名字
file_trainval = open(txtsavepath + '/trainval.txt', 'w')
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')
for i in range(num):
name = total_xml[i][:-4] + '\n'
if i in train_indices:
file_trainval.write(name)
elif i in test_indices:
file_train.write(name)
else:
file_val.write(name)
file_trainval.close()
file_train.close()
file_val.close()
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import os
from os import getcwd
"""
作用 1:把xml每一个图片对象转换成txt形式(每个txt表示一张图片,
txt里面每行表示图片里的一个object。
2:把之前训练,测试,验证集合三个txt里面图片名称改成全局路径
"""
sets = ['train', 'val', 'trainval']
classes = ["red", "green", "yellow", "off"] # 改成自己的类别
abs_path = os.getcwd()
print(abs_path)
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return x, y, w, h
def convert_annotation(image_id):
if image_id == '': return
in_file = open('data/mydata/Annotations/%s.xml' % (image_id), encoding='UTF-8')
out_file = open('data/mydata/labels/%s.txt' % (image_id), 'w')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
# difficult = obj.find('difficult').text
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))
b1, b2, b3, b4 = b
# 标注越界修正
if b2 > w:
b2 = w
if b4 > h:
b4 = h
b = (b1, b2, b3, b4)
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
for image_set in sets:
if not os.path.exists('data/mydata/labels/'):
os.makedirs('data/mydata/labels/')
image_ids = open('data/mydata/dataSet/%s.txt' % (image_set)).read().strip().split("\n")
list_file = open('data/mydata/%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write(abs_path + '/data/mydata/JPEGImages/%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
list_file.write(abs_path + ‘/data/mydata/JPEGImages/%s.jpg\n’ % (image_id))注意jpg格式写死了,可能会有图片为png,但这里为jpg的bug。
全修改为jpg脚本:
# import os
# def rename_files_in_folder(folder_path):
# for filename in os.listdir(folder_path):
# if filename.endswith(".png"):
# base = os.path.splitext(filename)[0]
# os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, base + ".jpg"))
# # 使用方法
# # replace 'your_folder_path' with the path of your folder
# rename_files_in_folder(r'E:\panda_ws-main\traffic_light\data\mydata\JPEGImages')
有时候txt里记录了1.jpg,但JPEGIMG里却缺少这张图片,报错。修改代码
# 复制图像到另一个文件夹
# 文件所在文件夹
import os
import shutil
with open(r"E:\panda_ws-main\traffic_light\data\mydata\dataSet\val.txt", 'r') as f:
for line in f.readlines():
line = line.strip('\n')
print(line)
if os.path.exists(line):
shutil.copy(line, r'E:\panda_ws-main\traffic_light\data\images')
其余按照网上流程都可以运行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。