背景:
这个代码其实很简单,但在写得过程中出现了一个小问题,记录下来,时刻警醒自己。
代码:
其中 json 文件中的内容如下:
[
{
"obj_id": "",
"obj_type": "car",
"psr": {
"position": {
"x": 27.93663999425515,
"y": 58.89653792211754,
"z": 0.88486
},
"rotation": {
"x": 0,
"y": 0,
"z": -2.9488393537400284
},
"scale": {
"x": 4.291998459011368,
"y": 1.9562478311251765,
"z": 1.769719
}
}
},
{
"obj_id": "",
"obj_type": "car",
"psr": {
"position": {
"x": -25.544781579415567,
"y": 58.919334668746274,
"z": 1.139473397260274
},
"rotation": {
"x": 0,
"y": 0,
"z": -2.2216651836602552
},
"scale": {
"x": 5.679734000489526,
"y": 2.2504801587853507,
"z": 2.2789457945205482
}
}
},
...
]
转换成的txt文件中的内容如下:
car 27.93663999425515 58.89653792211754 0.88486 4.291998459011368 1.9562478311251765 1.769719 -2.9488393537400284
car -25.544781579415567 58.919334668746274 1.139473397260274 5.679734000489526 2.2504801587853507 2.2789457945205482 -2.2216651836602552
non_motor_vehicles -16.690192264052445 67.47992328242128 0.727508 2.1920535765607565 0.8341996047449176 1.455016 -0.7850253537400286
...
代码为:
import json
import os
def convert_annotation(jsonpath,txtpath,json_file):
name = json_file.split('.')[0]
if not os.path.exists(txtpath):
os.makedirs(txtpath)
txtfile = os.path.join(txtpath, name + ".txt")
with open(jsonpath) as input_file:
with open(txtfile,"w+") as out_file:
json_data_list = json.load(input_file)
for json_data_key in json_data_list:
cls_id = json_data_key['obj_type']
x = json_data_key['psr']['position']['x']
y = json_data_key['psr']['position']['y']
z = json_data_key['psr']['position']['z']
l = json_data_key['psr']['scale']['x']
w = json_data_key['psr']['scale']['y']
h = json_data_key['psr']['scale']['z']
hz = json_data_key['psr']['rotation']['z']
data = (x,y,z,l,w,h,hz)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in data]) + '\n')
print(txtfile + " was written !!")
if __name__ == "__main__":
rootpath = "/xxx"
jsonpath = rootpath + os.sep + 'label'
txtpath = rootpath + os.sep + 'label2txt'
json_list = os.listdir(jsonpath)
for i in range(0, len(json_list)):
path = os.path.join(jsonpath, json_list[i])
if ('.json' in path):
print(path)
convert_annotation(path, txtpath, json_list[i])
print('done', i)
else:
print('not xml file', i)