json2yolo脚本
- yolo所对应的格式是.txt,其中包含框的类别索引,中心点坐标,boundingboxs的宽,高。
import json
import os
#由x1,y1,x2,y2 ---->Cx,Cy,W,H 相对位置(取值范围0-1)
name2id = {'person':0,'mask':1}#写好自己的类别和标签
def convert(img_size, box):
dw = 1./(img_size[0])#压缩到0-1之间
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)#返回中心点和WH
def decode_json(json_floder_path,json_name):
#转换好的标签路径(转换好的放哪)
txt_name = 'C:\\Users\\***\\AA-project\\pytorch\\PyTorch-YOLOv3\\data\\custom\\labels\\' + json_name[0:-5] + '.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'))
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路径
json_floder_path = 'C:\\Users\\***\\AA-project\\pytorch\\PyTorch-YOLOv3\\data\\custom\\label-test'
json_names = os.listdir(json_floder_path)
for json_name in json_names:
decode_json(json_floder_path,json_name)
标签:box,name,img,json,json2yolo,path,txt
From: https://www.cnblogs.com/lushuang55/p/17609455.html