YOLOV5——將 json 格式的標注數據轉化為 YOLO 需要的 txt 格式


YOLO需要的標注數據是每個圖片一個 txt 文件

json 標注數據文件內容包含:

name:圖片文件名

category:類別id

bbox:目標框信息xyrb格式,分別指[左上角x坐標,左上角y坐標,右下角x坐標,右下角y坐標]

score:預測的分數

如下格式

[
    {
        "name": "235_2_t20201127123021723_CAM2.jpg",
        "image_height": 6000,
        "image_width": 8192,
        "category": 5,
        "bbox": [
            1876.06,
            998.04,
            1883.06,
            1004.04
        ]
    },
    {
        "name": "235_2_t20201127123021723_CAM2.jpg",
        "image_height": 6000,
        "image_width": 8192,
        "category": 5,
        "bbox": [
            1655.06,
            1094.04,
            1663.06,
            1102.04
        ]
    },
    {
        "name": "235_2_t20201127123021723_CAM2.jpg",
        "image_height": 6000,
        "image_width": 8192,
        "category": 5,
        "bbox": [
            1909.06,
            1379.04,
            1920.06,
            1388.04
        ]
    }
]

 

我們需要將 json 中的數據轉化為每個文件一個 txt 文件

其中 yolo 需要的標注數據格式:

235_2_t20201127123021723_CAM2.txt 文件 

數據格式:類別id  中心點x坐標   中心點y坐標  w    h(相對於圖片寬高)

5 0.229438 0.16684 0.000854 0.001
5 0.202522 0.183007 0.000977 0.001333

json2txt 代碼

import os
import json


json_dir = 'train_annos.json'  # json文件路徑
out_dir = 'output/'  # 輸出的 txt 文件路徑


def main():
    # 讀取 json 文件數據
    with open(json_dir, 'r') as load_f:
        content = json.load(load_f)
    # 循環處理
    for t in content:
        tmp = t['name'].split('.')
        filename = out_dir + tmp[0] + '.txt'

        if os.path.exists(filename):
            # 計算 yolo 數據格式所需要的中心點的 相對 x, y 坐標, w,h 的值
            x = (t['bbox'][0] + t['bbox'][2]) / 2 / t['image_width']
            y = (t['bbox'][1] + t['bbox'][3]) / 2 / t['image_height']
            w = (t['bbox'][2] - t['bbox'][0]) / t['image_width']
            h = (t['bbox'][3] - t['bbox'][1]) / t['image_height']
            fp = open(filename, mode="r+", encoding="utf-8")
            file_str = str(t['category']) + ' ' + str(round(x, 6)) + ' ' + str(round(y, 6)) + ' ' + str(round(w, 6)) + \
                       ' ' + str(round(h, 6))
            line_data = fp.readlines()

            if len(line_data) != 0:
                fp.write('\n' + file_str)
            else:
                fp.write(file_str)
            fp.close()

        # 不存在則創建文件
        else:
            fp = open(filename, mode="w", encoding="utf-8")
            fp.close()


if __name__ == '__main__':
    main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM