format.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import json
  2. import os
  3. names = {
  4. "专注" : 0,
  5. "走神" : 1,
  6. "疲倦" : 2,
  7. "开小差" : 3,
  8. "老师" : 4
  9. }
  10. def format_label(json_file, out_path):
  11. """
  12. 输入json标准文件,转换为yolo的格式.txt
  13. 把x1, y1, w, h (w, h)-> cx, cy, w, h (0-1)
  14. 1. json_file:标准的数据文件
  15. 2. out_path:转换后的存放路径,转换后文件与json文件名字一样,扩展名txt
  16. """
  17. file_name = os.path.basename(json_file)
  18. only_name = file_name.split(".")[0]
  19. out_file = os.path.join(out_path, F"{only_name}.txt")
  20. # 打开文件,解析,并处理数据,输出到输出标签文件
  21. print(json_file)
  22. with open(json_file, encoding='utf-8') as fd:
  23. # 转换为字典
  24. json_data = json.load(fd)
  25. # print(json_data)
  26. is_labeled = json_data["labeled"]
  27. if is_labeled:
  28. # 打开输出文件
  29. out_fd = open(out_file, "w")
  30. img_h = json_data["size"]["height"]
  31. img_w = json_data["size"]["width"]
  32. objects = json_data["outputs"]["object"]
  33. for obj in objects:
  34. name = obj["name"]
  35. xmin = obj["bndbox"]["xmin"]
  36. ymin = obj["bndbox"]["ymin"]
  37. xmax = obj["bndbox"]["xmax"]
  38. ymax = obj["bndbox"]["ymax"]
  39. # 规范化
  40. w = float(xmax - xmin)
  41. h = float(ymax - ymin)
  42. centerx = xmin + w / 2
  43. centery = ymin + h /2
  44. w /= img_w
  45. h /= img_h
  46. centerx /= img_w
  47. centery /= img_h
  48. out_fd.write(F"{names[name]} {centerx:.6f} {centery:.6f} {w:.6f} {h:.6f}\n")
  49. out_fd.close()
  50. print(F"完成{json_file}的标注转换!")
  51. else:
  52. print(F"{json_file}没有标准")
  53. def to_yolo(in_path, out_path):
  54. if not (os.path.exists(in_path) and os.path.isdir(in_path)):
  55. return False
  56. if not os.path.exists(out_path):
  57. os.mkdir(out_path)
  58. all_files = os.listdir(in_path)
  59. for json_file in all_files:
  60. path_file = os.path.join(in_path, json_file)
  61. format_label(path_file, out_path)
  62. if __name__ == "__main__":
  63. to_yolo("./outputs", "yolo_labels")