参考链接:点击打开链接
我自己的数据集格式为filename lable xmin ymin xmax ymax
1 通过别的模板转换
VOC数据集的xml格式为:
<annotation>
<folder>VOC2007</folder>
<filename>000002.jpg</filename> //文件名
<size> //图像尺寸(长宽以及通道数
<width>335</width>
<height>500</height>
<depth>3</depth>
</size>
<object> //检测到的物体
<name>cat</name> //物体类别
<pose>Unspecified</pose> //拍摄角度
<truncated>0</truncated> //是否被截断(0表示完整
<difficult>0</difficult> //目标是否难以识别(0表示容易识别)
<bndbox> //bounding-box(包含左下角和右上角xy坐标)
<xmin>139</xmin>
<ymin>200</ymin>
<xmax>207</xmax>
<ymax>301</ymax>
</bndbox>
</object>
</annotation>
所以我们把它当作模板然后修改成自己的数据集。注意object
可能不止一个。
转换代码:
import copy
from lxml.etree import Element, SubElement, tostring, ElementTree
import cv2
# 修改为你自己的路径
template_file = 'G:\\dataset\\WJ-data\\anno.xml'
target_dir = 'G:\\dataset\\WJ-data\\Annotations\\'
image_dir = 'G:\\dataset\\train\\' # 图片文件夹
train_file = 'G:\\dataset\\train.txt' # 存储了图片信息的txt文件
with open(train_file) as f:
trainfiles = f.readlines() # 标注数据 格式(filename label x_min y_min x_max y_max)
file_names = []
tree = ElementTree()
for line in trainfiles:
trainFile = line.split()
file_name = trainFile[0]
print(file_name)
# 如果没有重复,则顺利进行。这给的数据集一张图片的多个框没有写在一起。
if file_name not in file_names:
file_names.append(file_name)
lable = trainFile[1]
xmin = trainFile[2]
ymin = trainFile[3]
xmax = trainFile[4]
ymax = trainFile[5]
tree.parse(template_file)
root = tree.getroot()
root.find('filename').text = file_name
# size
sz = root.find('size')
im = cv2.imread(image_dir + file_name)#读取图片信息
sz.find('height').text = str(im.shape[0])
sz.find('width').text = str(im.shape[1])
sz.find('depth').text = str(im.shape[2])
# object 因为我的数据集都只有一个框
obj = root.find('object')
obj.find('name').text = lable
bb = obj.find('bndbox')
bb.find('xmin').text = xmin
bb.find('ymin').text = ymin
bb.find('xmax').text = xmax
bb.find('ymax').text = ymax
# 如果重复,则需要添加object框
else:
lable = trainFile[1]
xmin = trainFile[2]
ymin = trainFile[3]
xmax = trainFile[4]
ymax = trainFile[5]
xml_file = file_name.replace('jpg', 'xml')
tree.parse(target_dir + xml_file)#如果已经重复
root = tree.getroot()
obj_ori = root.find('object')
obj = copy.deepcopy(obj_ori) # 注意这里深拷贝
obj.find('name').text = lable
bb = obj.find('bndbox')
bb.find('xmin').text = xmin
bb.find('ymin').text = ymin
bb.find('xmax').text = xmax
bb.find('ymax').text = ymax
root.append(obj)
xml_file = file_name.replace('jpg', 'xml')
tree.write(target_dir + xml_file, encoding='utf-8')
2.将xml转为符合YOLO的txt
标注文件.txt里的数据格式是这样的:
转换代码如下:
# box里保存的是ROI感兴趣区域的坐标(x,y的最大值和最小值)
# 返回值为ROI中心点相对于图片大小的比例坐标,和ROI的w、h相对于图片大小的比例
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)
# 对于单个xml的处理
def convert_annotation(image_add):
# image_add进来的是带地址的.jpg
#image_add = os.path.split(image_add,' ')[1] # 截取文件名
image_name = image_add.split()[0]
print(image_name)
image_name = image_name.replace('.jpg', '') # 删除后缀,现在只有文件名
in_file = open('G:\\dataset\\WJ-data\\Annotations\\' + image_name + '.xml') # 图片对应的xml地址
out_file = open('G:\\dataset\\WJ-data\\labels\\%s.txt' % (image_name), '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)
# 在一个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将索引与具体类别配对
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')
if not os.path.exists('G:\\dataset\\WJ-data\\labels\\'):#不存在文件夹
os.makedirs('G:\\dataset\\WJ-data\\labels\\')
image_adds = open("G:\\dataset\\train.txt")
for image_add in image_adds:
image_add = image_add.strip()
convert_annotation(image_add)
print("Finished")
3.构建训练集与交叉验证集:
"""
分割训练集和验证集
分别存储了图片的路径
"""
from sklearn.model_selection import train_test_split
img_add = 'G:\\dataset\\train.txt'
data_set = [x.strip() for x in open(img_add).readlines()]
train_X, test_X = train_test_split(data_set, test_size=0.2, random_state=0)
print(train_X)
print(test_X)
train_file = open('G:\\dataset\\WJ-data\\train_file.txt', 'w')
for x in train_X:
x = x.split(' ')[0]
print(x)
train_file.write('G:\\dataset\\train'+x+'\n')
test_file = open('G:\\dataset\\WJ-data\\valid_file.txt', 'w')
for x in test_X:
x = x.split(' ')[0]
test_file.write('G:\\dataset\\train'+x+'\n')
4. 生成类别名文件:
with open('G:\\dataset\\WJ-data\\obj.names', 'w') as f:
for i in range(61):
f.write(str(i)+'\n')
参考链接: