数据集制作之json转为yolo格式

首先json格式如下

不是该格式可以退出本博客

转化代码如下

import json
import os
classify_map = {
    'goose': 0,
}

def xyxy2xywh(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[2]) / 2 * dw
    y = (box[1] + box[3]) / 2 * dh
    w = (box[2] - box[0]) * dw
    h = (box[3] - box[1]) * dh
    return (x, y, w, h)  # 返回的都是标准化后的值


def voc2yolo(path):
    txt_out_path = r'E:\dataset\labels\test'  # 转换后txt保存路径
    for file in os.listdir(path):
        print(file)
        with open(os.path.join(path, file), 'r') as f:
            data = json.load(f)
            txt_name = file.split(".")[0] + ".txt"
            h = data['imageHeight']
            w = data['imageWidth']
            res = []
            for item in data['shapes']:
                classify = classify_map[item['label']]
                points = item['points']
                xmin = min(points[0][0], points[1][0])
                ymin = min(points[0][1], points[1][1])
                xmax = max(points[0][0], points[1][0])
                ymax = max(points[0][1], points[1][1])
                box = [float(xmin), float(ymin), float(xmax),
                   float(ymax)]
            # # 将x1, y1, x2, y2转换成yolov5所需要的x, y, w, h格式
                bbox = xyxy2xywh((w, h), box)
                res.append([classify,bbox])
            # # 写入目标文件中,格式为 id x y w h
            with open(os.path.join(txt_out_path, txt_name), 'w') as out_file:
                for classify, bbox in res:
                    out_file.write(str(classify) + " " + " ".join(str(x) for x in bbox) + '\n')
            out_file.close()

if __name__ == '__main__':
    # json格式数据路径
    path = r'E:\dataset\json\test'
    voc2yolo(path)

需要修改txt_out_path,path,classify_map

有问题可以在评论区询问,看到会回复

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值