1.创建txt文件的路径名
import os;
import shutil;
def listname(path,idtxtpath):
filelist = os.listdir(path);# 该文件夹下所有的文件(包括文件夹)
filelist.sort()
f = open(idtxtpath, 'w');
for files in filelist: # 遍历所有文件
Olddir = os.path.join(path, files); # 原来的文件路径
if os.path.isdir(Olddir): # 如果是文件夹则跳过
continue;
f.write(path)
f.write("/");
f.write(files);
f.write('\n');
f.close();
savepath = os.getcwd()
imgidtxttrainpath = savepath+"/trainImageId.txt"
imgidtxtvalpath = savepath + "/validateImageId.txt"
listname(savepath + "/train/images",imgidtxttrainpath)
listname(savepath + "/val/images",imgidtxtvalpath)
print "trainImageId.txt && validateImageId.txt have been created!"
2.labelimg标签做好后,有些图片有标签,有些没有,这时候如果全部放到yolo中训练的话,某些图片找不到对应的txt,则会出错,该脚本删除那些没有标签的图片
import shutil;
def delete(path):
savepath=os.getcwd()+"/saveimages";
isExists=os.path.exists(savepath);
if not isExists:
os.makedirs(savepath,493);
filelist=os.listdir(path);#该文件夹下所有的文件
filelist.sort()
for files in filelist:
pos=-1;
if "txt" in files:
print files;
filearray=files.split("-");
number=filearray[1].split(".");
picname=path+"/core-"+number[0]+".jpeg";
shutil.move(picname,savepath);
savepath=os.getcwd();
delete(savepath+"/2");
3.xml转txt
注意yolo需要的格式为
# -*- coding: utf-8 -*-
import os
import sys
import xml.etree.ElementTree as ET
import glob
def convert(size,box):
dw = 1./(size[0])
dh = 1./(size[1])
x = (box[0] + box[1])/2.0
y = (box[2] + box[3])/2.0
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 xml_to_txt(indir,outdir):
os.chdir(indir)
annotations = os.listdir('.')
annotations = glob.glob(r"*.xml")
for i, file in enumerate(annotations):
file_save = file.split('.')[0]+'.txt'
file_txt=os.path.join(outdir,file_save)
f_w = open(file_txt,'w')
in_file = open(file)
tree=ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
# 在一个XML中每个Object的迭代
for obj in root.iter('object'):
# iter()方法可以递归遍历元素/树的所有子元素
difficult = obj.find('difficult').text
cls = obj.find('name').text
# 如果训练标签中的品种不在程序预定品种,或者difficult = 1,跳过此object
#if cls not in classes or int(difficult) == 1:
# continue
#cls_id = classes.index(cls)#这里取索引,避免类别名是中文,之后运行yolo时要在cfg将索引与具体类别配对
cls_id=0
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))
bb = convert((w, h), b)
f_w.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
indir='./'
outdir='./'
xml_to_txt(indir,outdir)