format.py 2.2 KB

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