当前位置:   article > 正文

【目标检测】YOLO格式数据集txt标注转换为COCO格式JSON_目标检测数据集txt转json

目标检测数据集txt转json

YOLO格式数据集:

  1. images
  2. |--train
  3. |--test
  4. |--val
  5. labels
  6. |--train
  7. |--test
  8. |--val

代码:

  1. import os
  2. import json
  3. from PIL import Image
  4. # 设置数据集路径
  5. dataset_path = "path/to/your/dataset"
  6. images_path = os.path.join(dataset_path, "images")
  7. labels_path = os.path.join(dataset_path, "labels")
  8. # 类别映射
  9. categories = [
  10. {"id": 1, "name": "category1"},
  11. {"id": 2, "name": "category2"},
  12. # 添加更多类别
  13. ]
  14. # YOLO格式转COCO格式的函数
  15. def convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height):
  16. x_min = (x_center - width / 2) * img_width
  17. y_min = (y_center - height / 2) * img_height
  18. width = width * img_width
  19. height = height * img_height
  20. return [x_min, y_min, width, height]
  21. # 初始化COCO数据结构
  22. def init_coco_format():
  23. return {
  24. "images": [],
  25. "annotations": [],
  26. "categories": categories
  27. }
  28. # 处理每个数据集分区
  29. for split in ['train', 'test', 'val']:
  30. coco_format = init_coco_format()
  31. annotation_id = 1
  32. for img_name in os.listdir(os.path.join(images_path, split)):
  33. if img_name.lower().endswith(('.png', '.jpg', '.jpeg')):
  34. img_path = os.path.join(images_path, split, img_name)
  35. label_path = os.path.join(labels_path, split, img_name.replace("jpg", "txt"))
  36. img = Image.open(img_path)
  37. img_width, img_height = img.size
  38. image_info = {
  39. "file_name": img_name,
  40. "id": len(coco_format["images"]) + 1,
  41. "width": img_width,
  42. "height": img_height
  43. }
  44. coco_format["images"].append(image_info)
  45. if os.path.exists(label_path):
  46. with open(label_path, "r") as file:
  47. for line in file:
  48. category_id, x_center, y_center, width, height = map(float, line.split())
  49. bbox = convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height)
  50. annotation = {
  51. "id": annotation_id,
  52. "image_id": image_info["id"],
  53. "category_id": int(category_id) + 1,
  54. "bbox": bbox,
  55. "area": bbox[2] * bbox[3],
  56. "iscrowd": 0
  57. }
  58. coco_format["annotations"].append(annotation)
  59. annotation_id += 1
  60. # 为每个分区保存JSON文件
  61. with open(f"path/to/output/{split}_coco_format.json", "w") as json_file:
  62. json.dump(coco_format, json_file, indent=4)

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

闽ICP备14008679号