在项目的根目录下新建一个maketxt.py文件。
该脚本会在straw/ImageSets文件夹下生成:trainval.txt, test.txt, train.txt, val.txt,内容如下图所示,将图片分成了训练集,验证集和测试集,并将文件名(不带扩展名)汇总在txt文件中。
import os
import random
trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'F:\\straw\\label'
txtsavepath = 'F:\\straw\\Imageset'
total_xml = os.listdir(xmlfilepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)
ftrainval = open('F:\\straw\\Imageset\\trainval.txt', 'w')
ftest = open('F:\\straw\\Imageset\\test.txt', 'w')
ftrain = open('F:\\straw\\Imageset\\/train.txt', 'w')
fval = open('F:\\straw\\Imageset\\val.txt', 'w')
for i in list:
name = total_xml[i][:-4] + '\n'
if i in trainval:
ftrainval.write(name)
if i in train:
ftest.write(name)
else:
fval.write(name)
else:
ftrain.write(name)
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()
新建一个voc_label.py文件
此脚本将在straw文件夹下生成images和labels两个文件夹用于训练。images文件夹下储存训练图片,labels文件夹下储存相应的标签文件。这里的标签文件全部是由原xml文件转化而来的txt文件,且将坐标位置信息全部归一化处理,代码如下。
需要注意的是,代码中第9行的classes对应的是训练集中的标签,如果你使用本文中的训练集,那就无需改动;如果你使用自己的训练集,这里需要修改成你自己的标签。我这里是两个标签0和1
0代表草莓不成熟
1代表草莓成熟
后面具体名称可以用一个元组对应执行即可
import xml.etree.ElementTree as ET
import os
from os import getcwd
sets = ['train','test','val']
classes = ['0', '1']
def convert(size, box):
dw = 1.0 / size[0]
dh = 1.0 / 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 convert_annotation(image_id):
in_file = open('F:\\straw\\label\\%s.xml' % (image_id),encoding = "utf-8")
out_file = open('F:\\straw\\label_txt\\%s.txt' % (image_id),'w' ,encoding = "utf-8")
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
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))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
print(wd)
for image_set in sets:
if not os.path.exists('F:\\straw\\label_txt\\'):
os.makedirs('F:\\straw\\label_txt\\')
image_ids = open('F:\\straw\\Imageset\\%s.txt' % (image_set),encoding = "utf-8").read().strip().split()
list_file = open('F:\\straw\\Imageset\\%s.txt' % (image_set), 'w',encoding = "utf-8")
for image_id in image_ids:
list_file.write('F:\\straw\\image\\%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
这里我曾出现一个问题,具体好像是size不能为0
经过测试检查发现我标注的xml文件的size不知为啥为0
直接把代码的10,11行size【0】和size【1】改为对应的图片大小即可