想看懂代码的uu可以先了解一下yolo需要的txt数据格式是什么样的,还有BDD的json文件中的数据结构是什么样的。
想直接一键应用的看注释即可
import json
import os
import shutil
from pathlib import Path
Jsonpath = r'C:/Users/Xiaohu/Desktop/BDD100K/labels/det_val.json'
out_labels_path = r'C:/Users/Xiaohu/Desktop/BDD100K/labels/labels/val'
#labels normalized
#首先载入json文件
with open (Jsonpath,'r') as j:
Metadata = json.load(j)
#这里读取每张图片对应的列表(BDD的图片以列表形式存储)
for i,dict_pic in enumerate(Metadata):
category_value_list = []
n = dict_pic['name']
pic_name = Path(n).stem + '.txt'
if 'labels' in dict_pic:
list_labels = dict_pic['labels']
for dict_label in list_labels:
category_key = dict_label['category']
category_value = ClassDict[category_key]
category_value_list.append(category_value)
#这里是把json里的数据正则化或者说归一化
with open(os.path.join(out_labels_path, pic_name), 'a') as l:
w = 1280
h = 720
out_det = []
dict_dimension = dict_label['box2d']
x1 = dict_dimension['x1']
y1 = dict_dimension['y1']
x2 = dict_dimension['x2']
y2 = dict_dimension['y2']
xc = (x1 + x2) / (2* w)
yc = (y1 + y2) / (2 * h)
bw = (x2 - x1 )/ w
bh = (y2 - y1) / h
out_det.append('{:.6f}'.format(xc))
out_det.append('{:.6f}'.format(yc))
out_det.append('{:.6f}'.format(bw))
out_det.append('{:.6f}'.format(bh))
#逐行写入
line = str(category_value)
for coord in out_det:
line += ' ' + str(coord)
l.write(line)
l.write('\n')