BDD100K数据集之标签格式转换
⼀、将BDD100K数据集的json标签格式转换为VOC的xml标签格式
⾸先,我们需要两个辅助脚本:parseJson.py(⽤来解析json⾥⾯的对象检测部分的数据)和pascal_voc_io.py(创建VOC格式的xml,并把json⽂件的数据填充到xml)。
1、parseJson.py
```
#!/usr/bin/env python
# -*- coding: utf8 -*-
#parse json,input json filename,output info needed by voc
import json
#这⾥是我需要的10个类别
categorys = ['car', 'bus', 'person', 'bike', 'truck', 'motor', 'train', 'rider', 'traffic sign', 'traffic light']
def parseJson(jsonFile):
'''
params:
jsonFile -- BDD00K数据集的⼀个json标签⽂件
return:
返回⼀个列表的列表,存储了⼀个json⽂件⾥⾯的⽅框坐标及其所属的类,
形如:[[325, 342, 376, 384, 'car'], [245, 333, 336, 389, 'car']]
'''
objs = []
obj = []
f = open(jsonFile)
info = json.load(f)
objects = info['frames'][0]['objects']
for i in objects:
if(i['category'] in categorys):
obj.append(int(i['box2d']['x1']))
obj.append(int(i['box2d']['y1']))
obj.append(int(i['box2d']['x2']))
obj.append(int(i['box2d']['y2']))
obj.append(i['category'])
objs.append(obj)
obj = []
#print("objs",objs)
return objs
#test
#result = parseJson("/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/labels/100k/val/b1c9c847-3bda4659.json")
#print(len(result))
#print(result)
```
2、pascal_voc_io.py
```
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import os
import ElementTree
ElementTree import Element, SubElement
from lxml import etree
from xml.dom.minidom import parseString
class PascalVocWriter:
def __init__(self, foldername, filename, imgSize, databaseSrc='Unknown', localImgPath=None):
'''
params:
foldername -- 要存储的xml⽂件的⽗⽬录
filename -- xml⽂件的⽂件名
imgSize -- 图⽚的尺⼨
databaseSrc -- 数据库名,这⾥不需要,默认为Unknown
localImaPath -- xml⽂件⾥⾯的<path></path>标签的内容
'''
self.foldername = foldername
self.filename = filename
self.databaseSrc = databaseSrc
self.imgSize = imgSize
self.boxlist = []
self.localImgPath = localImgPath
def prettify(self, elem):
"""
params:
elem -- xml的根标签,以<annotation>开始
return:
返回⼀个美观输出的xml(⽤到minidom),本质是⼀个str
"""
xml = string(elem)
dom = parseString(xml)
# prettyxml(' '))
prettifyResult = prettyxml(' ')
return prettifyResult
def genXML(self):
"""
return:
⽣成⼀个VOC格式的xml,返回⼀个xml的根标签,以<annotation>开始
"""
# Check conditions
if self.filename is None or \
self.foldername is None or \
self.imgSize is None or \
len(self.boxlist) <= 0:
return None
top = Element('annotation') # 创建⼀个根标签<annotation>
folder = SubElement(top, 'folder') # 在根标签<annotation>下创建⼀个⼦标签<folder>
< = self.foldername # ⽤self.foldername的数据填充⼦标签<folder>
filename = SubElement(top, 'filename') # 在根标签<annotation>下创建⼀个⼦标签<filename> = self.filename # ⽤self.filename的数据填充⼦标签<filename>
localImgPath = SubElement(top, 'path') # 在根标签<annotation>下创建⼀个⼦标签<path> = self.localImgPath # ⽤self.localImgPath的数据填充⼦标签<path>
source = SubElement(top, 'source') # 在根标签<annotation>下创建⼀个⼦标签<source>
database = SubElement(source, 'database') # 在根标签<source>下创建⼀个⼦标签<database> = self.databaseSrc # ⽤self.databaseSrc的数据填充⼦标签<database>
size_part = SubElement(top, 'size') # 在根标签<annotation>下创建⼀个⼦标签<size>
width = SubElement(size_part, 'width') # 在根标签<size>下创建⼀个⼦标签<width>
height = SubElement(size_part, 'height') # 在根标签<size>下创建⼀个⼦标签<height>
depth = SubElement(size_part, 'depth') # 在根标签<size>下创建⼀个⼦标签<depth>
< = str(self.imgSize[1]) # ⽤self.imgSize[1]的数据填充⼦标签<width>
< = str(self.imgSize[0]) # ⽤self.imgSize[0]的数据填充⼦标签<height>
if len(self.imgSize) == 3: # 如果图⽚深度为3,则⽤self.imgSize[2]的数据填充⼦标签<height>,否则⽤1填充 = str(self.imgSize[2])
else:
< = '1'
segmented = SubElement(top, 'segmented')
< = '0'
return top
def addBndBox(self, xmin, ymin, xmax, ymax, name):
'''
将检测对象框坐标及其对象类别作为⼀个字典加⼊到self.boxlist中
params:
xmin -- 检测框的左上⾓的x坐标
ymin -- 检测框的左上⾓的y坐标
xmax -- 检测框的右下⾓的x坐标
ymax -- 检测框的右下⾓的y坐标
name -- 检测框内的对象类别名
'''
bndbox = {'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax} bndbox['name'] = name
self.boxlist.append(bndbox)
def appendObjects(self, top):
'''
在xml⽂件中加⼊检测框的坐标及其对象类别名
params:
top -- xml的根标签,以<annotation>开始
'''
for each_object in self.boxlist:
object_item = SubElement(top, 'object')
name = SubElement(object_item, 'name')
< = str(each_object['name'])
pose = SubElement(object_item, 'pose')
< = "Unspecified"
truncated = SubElement(object_item, 'truncated')
< = "0"
difficult = SubElement(object_item, 'Difficult')
< = "0"
bndbox = SubElement(object_item, 'bndbox')
xmin = SubElement(bndbox, 'xmin')
< = str(each_object['xmin'])
ymin = SubElement(bndbox, 'ymin')
< = str(each_object['ymin'])
xmax = SubElement(bndbox, 'xmax')
< = str(each_object['xmax'])
ymax = SubElement(bndbox, 'ymax')
< = str(each_object['ymax'])
def save(self, targetFile=None):
'''
以美观输出的xml格式来保存xml⽂件
params:
targetFile -- 存储的xml⽂件名,不包括.xml部分
'''
root = XML()
self.appendObjects(root)
out_file = None
subdir = self.foldername.split('/')[-1]
if not os.path.isdir(subdir):
os.mkdir(subdir)
if targetFile is None:
with open(self.foldername+'/'+self.filename + '.xml', 'w') as out_file: prettifyResult = self.prettify(root)
out_file.write(prettifyResult)
out_file.close()
else:
with open(targetFile, 'w') as out_file:
prettifyResult = self.prettify(root)
out_file.write(prettifyResult)
out_file.close()
class PascalVocReader:
def __init__(self, filepath):
# shapes type:
# [labbel, [(x1,y1), (x2,y2), (x3,y3), (x4,y4)], color, color]
self.shapes = []
self.filepath = filepath
self.parseXML()
def getShapes(self):
return self.shapes
def addShape(self, label, bndbox):
xmin = int(bndbox.find('xmin').text)
ymin = int(bndbox.find('ymin').text)
xmax = int(bndbox.find('xmax').text)
ymax = int(bndbox.find('ymax').text)
points = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
self.shapes.append((label, points, None, None))
def parseXML(self):
assert dswith('.xml'), "Unsupport file format"
parser = etree.XMLParser(encoding='utf-8')
xmltree = ElementTree.parse(self.filepath, parser=parser).getroot()
filename = xmltree.find('filename').text
for object_iter in xmltree.findall('object'):
bndbox = object_iter.find("bndbox")
label = object_iter.find('name').text
self.addShape(label, bndbox)
return True
# tempParseReader = PascalVocReader('l')
# Shapes()
#"""
# Test
#tmp = PascalVocWriter('temp','test', (10,20,3))
#tmp.addBndBox(10,10,20,30,'chair')
#tmp.addBndBox(1,1,600,600,'car')
#tmp.save()
#"""
```
3、bdd2voc.py
```
# -*- coding: utf8 -*-
import os
import pascal_voc_io
import parseJson
def main(srcDir, dstDir):
i = 1
# os.walk()
# dirName是你所要遍历的⽬录的地址, 返回的是⼀个三元组(root,dirs,files)
# root所指的是当前正在遍历的这个⽂件夹的本⾝的地址
# dirs是⼀个 list ,内容是该⽂件夹中所有的⽬录的名字(不包括⼦⽬录)
# files 同样是 list , 内容是该⽂件夹中所有的⽂件(不包括⼦⽬录)
for dirpath, dirnames, filenames in os.walk(srcDir):
# print(dirpath, dirnames, filenames)
for filepath in filenames:
fileName = os.path.join(dirpath,filepath)
print(fileName)
print("processing: {}, {}".format(i, fileName))
i = i + 1
xmlFileName = filepath[:-5] # remove ".json" 5 character
# 解析该json⽂件,返回⼀个列表的列表,存储了⼀个json⽂件⾥⾯的所有⽅框坐标及其所属的类objs = parseJson.parseJson(str(fileName))
# 如果存在检测对象,创建⼀个与该json⽂件具有相同名的VOC格式的xml⽂件
if len(objs):
tmp = pascal_voc_io.PascalVocWriter(dstDir, xmlFileName, (720,1280,3), fileName)
for obj in objs:
tmp.addBndBox(obj[0],obj[1],obj[2],obj[3],obj[4])
tmp.save()
else:
print(fileName)
if __name__ == '__main__':
# test
# these paths should be your own path
# srcDir = '/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/labels/100k/val'
# dstDir = '/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/Annotations/val'
srcDir = '/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/labels/100k/train'
dstDir = '/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/Annotations/train'
main(srcDir, dstDir)
```
⼆、将xml标签格式转换为darknet的txt标签格式
xml_to_yolo_txt.py
getsavefilename```
import glob
ElementTree as ET
# 类名
class_names = ['car', 'bus', 'person', 'bike', 'truck', 'motor', 'train', 'rider', 'traffic sign', 'traffic light']
# 转换⼀个xml⽂件为txt
def single_xml_to_txt(xml_file):
tree = ET.parse(xml_file)
root = t()
# 保存的txt⽂件路径
txt_file = xml_file.split('.')[0]+'.txt'
with open(txt_file, 'w') as txt_file:
for member in root.findall('object'):
#filename = root.find('filename').text
picture_width = int(root.find('size')[0].text)
picture_height = int(root.find('size')[1].text)
class_name = member[0].text
# 类名对应的index
class_num = class_names.index(class_name)
box_x_min = int(member[4][0].text) # 左上⾓横坐标
box_y_min = int(member[4][1].text) # 左上⾓纵坐标
box_x_max = int(member[4][2].text) # 右下⾓横坐标
box_y_max = int(member[4][3].text) # 右下⾓纵坐标
# 转成相对位置和宽⾼
x_center = (box_x_min + box_x_max) / (2 * picture_width)
y_center = (box_y_min + box_y_max) / (2 * picture_height)
width = (box_x_max - box_x_min) / (2 * picture_width)
height = (box_y_max - box_y_min) / (2 * picture_height)
print(class_num, x_center, y_center, width, height)
txt_file.write(str(class_num) + ' ' + str(x_center) + ' ' + str(y_center) + ' ' + str(width) + ' ' + str(height) + '\n') # 转换⽂件夹下的所有xml⽂件为txt
def dir_xml_to_txt(path):
i=1
for xml_file in glob.glob(path + '*.xml'):
print("processing {}, {}".format(i, xml_file+'.xml'))
single_xml_to_txt(xml_file)
i += 1
def main(path):
dir_xml_to_txt(path)
if __name__ == '__main__':
# xml⽂件路径
path = '/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/Annotations/train/'
#path = '/media/xavier/SSD256/global_datasets/BDD00K/bdd100k/Annotations/val/'
main(path)
```
运⾏该脚本python xml_to_yolo_txt.py,会在原来xml所在⽬录⽣成相同名的txt⽂件
```
# 移动验证集标签
mv /media/xavier/SSD256/global_datasets/BDD00K/bdd100k/labels/100k/val/*txt
/media/xavier/SSD256/darknet/bdd100k_data/val_labels/
# 移动训练集标签
mv /media/xavier/SSD256/global_datasets/BDD00K/bdd100k/labels/100k/train/*txt

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。