labelme的json文件转换为yolo标签格式

1. json格式说明

{
  "shapes": [
    {
      "points": [
        [
          463.23809523809524,
          380.8095238095238
        ],
        [
          550.8571428571428,
          425.57142857142856
        ]
      ],
      "shape_type": "rectangle",
      "flags": {},
      "label": "TT",
      "group_id": null
    },
    {
      "points": [
        [
          329.90476190476187,
          397.0
        ],
        [
          378.4761904761905,
          431.2857142857143
        ]
      ],
      "shape_type": "rectangle",
      "flags": {},
      "label": "car",
      "group_id": null
    }
  ],
  "imageData":......,
  "imagePath": "0073.jpg",
  "imageHeight": 720,
  "version": "4.2.10",
  "flags": {},
  "imageWidth": 1280
}

其中重要的参数有shapes shape_type imagePath

    shapes: 其中包含了标注的具体信息,由列表组成,每一个元素是一个字典,一个字典包含了一个标注框的相关信息;

label是标签;

points是标注的点,points的取值与shape_type相关,这里取的是rectangle即直接由矩形的对角线上两点确定一个矩形框。因此points中也只有两个点的信息,点的坐标为(x,y) ,坐标轴原点在左上角,原点向下为y正向,向右为x正向。

imagePath: 标注图片的文件名
shape_type: 记录了标记时选择的方式。

2. 格式转化

import json
import os

classes = ['car', 'Truck', 'person', 'bicycle', 'bus']


def convert(img_size, box):
    x1 = box[0]
    y1 = box[1]
    x2 = box[2]
    y2 = box[3]

    x_center = ((x2 + x1) / 2 - 1) / img_size[0]
    y_center = ((y2 + y1) / 2 - 1) / img_size[1]
    w = (x2 - x1) / img_size[0]
    h = (y2 - y1) / img_size[1]

    return (x_center, y_center, w, h)


def decode_json(json_floder_path, json_name):
    txt_name = '/home/zhy/Documents/智能驾驶项目/标注/txt/' + 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='utf-8'))

    img_w = data['imageWidth']
    img_h = data['imageHeight']

    for i in data['shapes']:

        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])

            classname = i['label']
            cls_id = classes.index(classname)

            bb = (x1, y1, x2, y2)
            bbox = convert((img_w, img_h), bb)
            txt_file.write(str(cls_id) + " " + " ".join([str(a) for a in bbox]) + '\n')


if __name__ == "__main__":

    json_floder_path = '/home/zhy/Documents/智能驾驶项目/标注/json/'
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        decode_json(json_floder_path, json_name)


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值