在使用YOLOv5的过程中,标签由json转变为txt文本的时候出现问题,报错了,不知道哪里出错了,是不是标签的命名上?
import json
import os
name2id = {'cone_pointer': 0, 'ball_pointer': 1, 'T_pointer': 2, '20_20_scale': 3, '3_30_scale': 4, '10_100_scale': 5,
'LED_1': 6, 'LED_HORIBA': 7, 'LED_circle_blue': 8, 'LED_rectangle_blue': 9, 'LED_yellow_mode': 10,
'shell_ball': 11, 'shell_cone_T': 12, 'shell_aluminium': 13, 'sensor_1': 14, 'red_float': 15} # 标签名称
def convert(img_size, box):
dw = 1. / (img_size[0])
dh = 1. / (img_size[1])
x = (box[0] + box[2]) / 2.0 - 1
y = (box[1] + box[3]) / 2.0 - 1
w = box[2] - box[0]
h = box[3] - box[1]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def decode_json(json_floder_path, json_name):
txt_name = 'C:\\yolov5\\Meter_Collection\\datasets\\labels\\train\\txt' + json_name[0:-5] + '.txt'
# 存放txt的绝对路径
txt_file = open(txt_name, 'w')
json_path = os.path.join(json_floder_path, json_name)
data = json.load(open(json_path, 'r', encoding='gb2312', errors='ignore'))
img_w = data['imageWidth']
img_h = data['imageHeight']
for i in data['shapes']:
label_name = i['label']
if (i['shape_type'] == 'rectangle'):
x1 = int(i['points'][0][0])
y1 = int(i['points'][0][1])
x2 = int(i['points'][1][0])
y2 = int(i['points'][1][1])
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb)
txt_file.write(str(name2id[label_name]) + " " + " ".join([str(a) for a in bbox]) + '\n')
if __name__ == "__main__":
json_floder_path = 'C:\\yolov5\\Meter_Collection\\datasets\\labels\\train\\json'
# 存放json的文件夹的绝对路径
json_names = os.listdir(json_floder_path)
for json_name in json_names:
decode_json(json_floder_path, json_name)
报错内容如下:
C:\ProgramData\Anaconda3\envs\yolov5_38\python.exe C:/yolov5/json_txt.py
Traceback (most recent call last):
File "C:/yolov5/json_txt.py", line 54, in
decode_json(json_floder_path, json_name)
File "C:/yolov5/json_txt.py", line 45, in decode_json
txt_file.write(str(name2id[label_name]) + " " + " ".join([str(a) for a in bbox]) + '\n')
KeyError: '20_200_sacle'
Process finished with exit code 1
遇到瓶颈了,希望解答一下。