COCO數據集: JSON轉txt
JSON文件示例


代碼
#COCO 格式的數據集轉化為 YOLO 格式的數據集
#--json_path 輸入的json文件路徑
#--save_path 保存的文件夾名字,默認為當前目錄下的labels。
import os
import json
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
#這里根據自己的json文件位置,換成自己的就行
parser.add_argument('--json_path', default='D:/A4-python/JSON/annotations.json',type=str, help="input: coco format(json)")
#這里設置.txt文件保存位置
parser.add_argument('--save_path', default='D:/A4-python/JSON/OP', type=str, help="specify where to save the output dir of labels")
arg = parser.parse_args()
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
#round函數確定(xmin, ymin, xmax, ymax)的小數位數
x = round(x * dw, 6)
w = round(w * dw, 6)
y = round(y * dh, 6)
h = round(h * dh, 6)
return (x, y, w, h)
if __name__ == '__main__':
json_file = arg.json_path # COCO Object Instance 類型的標注
ana_txt_save_path = arg.save_path # 保存的路徑
data = json.load(open(json_file, 'r'))
if not os.path.exists(ana_txt_save_path):
os.makedirs(ana_txt_save_path)
id_map = {} # coco數據集的id不連續!重新映射一下再輸出!
with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
# 寫入classes.txt
for i, category in enumerate(data['categories']):
f.write(f"{category['name']}\n")
id_map[category['id']] = i
# print(id_map)
#這里需要根據自己的需要,更改寫入圖像相對路徑的文件位置。
list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
for img in tqdm(data['images']):
filename = img["file_name"]
img_width = img["width"]
img_height = img["height"]
img_id = img["id"]
head, tail = os.path.splitext(filename)
ana_txt_name = head + ".txt" # 對應的txt名字,與jpg一致
f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
for ann in data['annotations']:
if ann['image_id'] == img_id:
box = convert((img_width, img_height), ann["bbox"])
f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
f_txt.close()
#將圖片的相對路徑寫入train2017或val2017的路徑
list_file.write('./images/train2017/%s.jpg\n' %(head))
list_file.close()
參考代碼鏈接
詳細!正確!COCO數據集(.json)訓練格式轉換成YOLO格式(.txt)
結果展示


Tips
- 文件夾的名字不能包含 \ / : * ? " < > |