当前位置:   article > 正文

json2yolo

json2yolo

写了一个labelme的rectangle json文件转yolo格式的脚本,欢迎点赞使用~~~

话不多说直接上代码~

  1. import json
  2. import glob
  3. def load(file,out_dir):
  4. # YOLOv5使用的标签映射,将LabelMe标签映射到对应的类别索引
  5. label_mapping = {
  6. 'box': 0,
  7. }
  8. path = glob.glob(f'{file}\*.json')
  9. for i in path:
  10. try:
  11. with open(i, 'r',encoding='utf-8') as f:
  12. data = json.load(f)
  13. # 转换每个标注
  14. yolo_annotations = []
  15. for annotation in data['shapes']:
  16. label = annotation['label']
  17. class_index = label_mapping.get(label)
  18. if class_index is not None:
  19. x, y = annotation['points'][0]
  20. width = annotation['points'][1][0] - x
  21. height = annotation['points'][1][1] - y
  22. x_center = (x + width / 2) / data['imageWidth']
  23. y_center = (y + height / 2) / data['imageHeight']
  24. width /= data['imageWidth']
  25. height /= data['imageHeight']
  26. yolo_annotations.append(f"{class_index} {abs(x_center)} {abs(y_center)} {abs(width)} {abs(height)}")
  27. name = i.split('.')[0].split('\\')[1]
  28. # 将转换后的标注写入txt文件
  29. with open(f'{out_dir}\{name}.txt', 'w') as f:
  30. for annotation in yolo_annotations:
  31. f.write(annotation + '\n')
  32. except:
  33. print(i)
  34. pass
  35. json_dir = 'js'
  36. out_dir='txt'
  37. load(json_dir,out_dir)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/275839
推荐阅读
相关标签
  

闽ICP备14008679号