12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import json
- import os
- names = {
- "专注" : 0,
- "走神" : 1,
- "疲倦" : 2,
- "开小差" : 3,
- "老师" : 4
- }
- def format_label(json_file, out_path):
- """
- 输入json标准文件,转换为yolo的格式.txt
- 把x1, y1, w, h (w, h)-> cx, cy, w, h (0-1)
- 1. json_file:标准的数据文件
- 2. out_path:转换后的存放路径,转换后文件与json文件名字一样,扩展名txt
- """
- file_name = os.path.basename(json_file)
- only_name = file_name.split(".")[0]
- out_file = os.path.join(out_path, F"{only_name}.txt")
- # 打开文件,解析,并处理数据,输出到输出标签文件
- print(json_file)
- with open(json_file, encoding='utf-8') as fd:
- # 转换为字典
- json_data = json.load(fd)
- # print(json_data)
- is_labeled = json_data["labeled"]
- if is_labeled:
- # 打开输出文件
- out_fd = open(out_file, "w")
- img_h = json_data["size"]["height"]
- img_w = json_data["size"]["width"]
- objects = json_data["outputs"]["object"]
- for obj in objects:
- name = obj["name"]
- xmin = obj["bndbox"]["xmin"]
- ymin = obj["bndbox"]["ymin"]
- xmax = obj["bndbox"]["xmax"]
- ymax = obj["bndbox"]["ymax"]
- # 规范化
- w = float(xmax - xmin)
- h = float(ymax - ymin)
- centerx = xmin + w / 2
- centery = ymin + h /2
- w /= img_w
- h /= img_h
- centerx /= img_w
- centery /= img_h
- out_fd.write(F"{names[name]} {centerx:.6f} {centery:.6f} {w:.6f} {h:.6f}\n")
- out_fd.close()
- print(F"完成{json_file}的标注转换!")
- else:
- print(F"{json_file}没有标准")
- def to_yolo(in_path, out_path):
- if not (os.path.exists(in_path) and os.path.isdir(in_path)):
- return False
- if not os.path.exists(out_path):
- os.mkdir(out_path)
-
- all_files = os.listdir(in_path)
- for json_file in all_files:
- path_file = os.path.join(in_path, json_file)
- format_label(path_file, out_path)
- if __name__ == "__main__":
- to_yolo("./outputs", "yolo_labels")
-
|