关键点检测数据格式转换(.JSON转TXT)
一、 JSON格式转Txt
import json
import osjson_path = r'C:\Users\PC\Desktop\2000张标注完-json文件\Json' # json文件路径
txt_path = r'C:\Users\PC\Desktop\2000张标注完-json文件\Txt' # txt文本文件路径
# 关键点数组(这里我写的是人体的7个关键点,大家可以改成自己标注顺序的关键点数组)
pointsArr = ["yading", "jiejian1", "jiejian2", "caizhai", "jiejian3","yezhongxin","jiejian4",]# 坐标归一化,返回中心点坐标和宽高
def coordinates2yolo(xmin, ymin, xmax, ymax, img_w, img_h):x = abs(xmin + xmax) / (2.0 * img_w)y = abs(ymin + ymax) / (2.0 * img_h)w = abs(xmax - xmin) / (1.0 * img_w)h = abs(ymax - ymin) / (1.0 * img_h)return x, y, w, hdef writeJson(rootpath, rootpath1, filename):path = os.path.join(rootpath, filename + '.json')count = 0 # 记录一张图片中人数的多少index = 0 # data索引,用于区分json文件中的label值with open(path) as f:# 读取json格式文件并获取相应信息data = json.load(f)imageHeight = data['imageHeight']imageWidth = data['imageWidth']data = data['shapes']length = len(data)# print('length', length)# 遍历json文件,用变量count记录 data[i]['label']=’类别名‘ 的次数,以此说明图片中有几个人for i in range(0, length):# 类别名换成自己的类别,当有多个类别时,用关键字or进行连接# if data[i]['label'] == '类别名1' or data[i]['label'] == '类别名2'。。。if data[i]['label'] == 'nenshao':count += 1# 将json文件信息写入txt文本文件中file = open(os.path.join(rootpath1, filename + '.txt'), mode='w')for j in range(0, count):# 在txt文本文件中写入类别id、目标框中心坐标以及图片宽高file.write(str(data[index]['group_id']))file.write(" ")points = data[index]['points']xmin = points[0][0]ymin = points[0][1]xmax = points[1][0]ymax = points[1][1]x, y, w, h = coordinates2yolo(xmin, ymin, xmax, ymax, imageWidth, imageHeight)file.write(str(round(x, 6)))file.write(" ")file.write(str(round(y, 6)))file.write(" ")file.write(str(round(w, 6)))file.write(" ")file.write(str(round(h, 6)))file.write(" ")index += 1# 在txt文本文件中写入关键点坐标与对应id值for point in pointsArr:# print(index)if index < length:if data[index]['label'] == point:point = data[index]['points'] # 获取关键点的坐标值file.write(str(round(point[0][0] / imageWidth, 6)))file.write(" ")file.write(str(round(point[0][1] / imageHeight, 6)))file.write(" ")# data[index]['group_id'] == 1,表名为被遮挡的关键点,在txt文档中写入1if data[index]['group_id'] == 1:file.write('1.000000')file.write(" ")# data[index]['group_id'] != 1,表名为正常标记的关键点,在txt文档中写入2else:file.write('2.000000')file.write(" ")index += 1# 若data[index]['label'] != point,则写入(0, 0, 0),前两个代表坐标,最后一个‘0’代表此关键点未被标记else:file.write('0.000000')file.write(" ")file.write('0.000000')file.write(" ")file.write('0.000000')file.write(" ")else:file.write('0.000000')file.write(" ")file.write('0.000000')file.write(" ")file.write('0.000000')file.write(" ")file.write('\n')# 读取path路径中的文件
filenames = os.listdir(json_path)
for item in filenames:# 以'.'为标志分割获取文件名filename = item.split('.')[0]print(filename)writeJson(json_path, txt_path, filename)
二、本人数据标注格式
使用软件为labelme
框为nenshao(ID:0)
第一个点为yading
第二个点为jiejian1
第三个点为jiejian2
第四个点为caizhai
第五个点为jiejian3
第六个点为yezhongxin
第七个点为jiejian4
在图像内且被遮挡住的点(ID:1)
示例: