最近一直在训练yolov8-pose的模型,网上有很多将coco的json转成yolo的json,但是对我来说并不适用。
第一个问题是数据不是56个,我标注的图片有多人的,它转换的时候并没有第一个人结束后换行,而是把所有数据连在一起
第二个问题是归一化的时候有问题,数据正常来说都是0-1之间,而用网上的代码转换的时候,数据有的时候超过了1,因此我自己写了一个脚本适用于多人的标注图片
import glob
import json
import os
def convert(height, width, box):
dw = 1. / width
dh = 1. / height
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
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)
# 只需要改路径即可 保存路径默认和此文件在同一目录下
jsonPath = "/home/data/yolo_train/22/"
for path, dddddd, file_name in os.walk(jsonPath):
json_file = glob.glob(os.path.join(path, '*.json'))
for i in json_file:
data = json.load(open(i, 'r'))
for img in data['images']:
id = img['id']
img_height = img['height']
img_width = img['width']
name = img['file_name']
# print(name)
head, tail = os.path.splitext(name)
head = head + ".txt"
j = -1
for i in head:
j += 1
if i == "/":
txt_name = head[j+1:]
f_txt = open( "txt/" + txt_name, 'w')
for img1 in data['annotations']:
img1_id = img1['image_id']
bbox = img1['bbox']
if img1_id == id:
bbox = convert(img_height, img_width, bbox)
f_txt.write("%s %s %s %s %s" % (0, bbox[0], bbox[1], bbox[2], bbox[3]))
count = 0
for i in range(len(img1["keypoints"])):
if count == 0 and (i + 1) % 3 != 0:
f_txt.write(" %s" % format(img1["keypoints"][i] / img_width, '6f'))
count = 1
elif count == 1 and (i + 1) % 3 != 0:
f_txt.write(" %s" % format(img1["keypoints"][i] / img_height, '6f'))
count = 0
elif (i + 1) % 3 == 0:
f_txt.write(" %s" % format(img1["keypoints"][i], '6f'))
count = 0
if i + 1 == 51:
f_txt.write("\n")
f_txt.close()
已经验证过了,可以直接使用。