栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python转换json标签文件格式为YOLO的.txt格式

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python转换json标签文件格式为YOLO的.txt格式

有些目标检测数据集中的标注文件为.json格式,包含了目标类别、目标框绝对坐标,如下图:

将其转换为YOLO适用的.txt格式,包含(类别 中心点的x 中心点的y 宽度w 高度h),如下图: 

 

代码如下:

'''
将json文件转为yolo所需要的txt文件。将未转换的标注放入labels文件夹中,图片放入images文件夹中
json中[x1,y1,x2,y2],(x1,y1)表示目标左上角坐标,(x2,y2)表示目标右下角坐标,图片左上角坐标为(0,0)
yolo的txt中[class,x_center,y_center,width,height](需要根据图片宽高进行归一化处理)
'''

import json
import os
from PIL import Image


def convert(img_size, box):  # 坐标转换
    dw = 1. / (img_size[0])
    dh = 1. / (img_size[1])
    x = (box[0] + box[2]) / 2.0
    y = (box[1] + box[3]) / 2.0
    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 = 'D:/json_to_txt/lable/' + 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='utf-8'))

    image_path = 'D:/json_to_txt/images/' + json_name[0:-5] + '.jpg'  # 图片存放路径

    # 使用pillow读取图片,获取图片的宽和高
    img_pillow = Image.open(image_path)
    img_w = img_pillow.width  # 图片宽度
    img_h = img_pillow.height  # 图片高度

   
    for i in data['Annotations']:      

        if i['classname'] == 'face_no_mask':  # 目标的类别
            x1, y1, x2, y2 = i['BoundingBox']    

            bb = (x1, y1, x2, y2)
            bbox = convert((img_w, img_h), bb)
            txt_file.write('0' + " " + " ".join([str(a) for a in bbox]) + 'n')  # 此处将该目标类别记为“0”

        if i['classname'] == 'face_with_mask':  # 目标的类别
            x1, y1, x2, y2 = i['BoundingBox']  

            bb = (x1, y1, x2, y2)
            bbox = convert((img_w, img_h), bb)
            txt_file.write('1' + " " + " ".join([str(a) for a in bbox]) + 'n')  # 此处将该目标类别记为“1”


if __name__ == "__main__":

    json_floder_path = 'D:/json_to_txt/lables/'  # json文件的路径
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        decode_json(json_floder_path, json_name)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005479.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号