当前位置:   article > 正文

将COCO格式的json文件转化为DOTA格式标签的代码实现_coco转dota

coco转dota

用oriented bounding box网络训练自己的数据集时,发现基本是针对DOTA数据集格式的,自己的数据集是labelme多边形标注,再转化成COCO格式的,写了一个小脚本把它再转化成DOTA格式。 

DOTA数据集标签:

保存在具有相同文件名的文本文件中(image_name.txt)

标签格式为:

 

 

x1 y1 x2 y2 x3 y3 x4 y4 category difficult

转化思路:

1、获取COCO.json文件中的“annotation”信息,保存category_id、image_id、annotation_id;

2、通过image_id从json中的“images”里获取到文件名;通过category_id和自己数据集里的类别矩阵our_category获取该实例对应的类别;

3、对多边形轮廓点求最小外接矩形;

4、输出矩形四个坐标点的取整值、类别名称,difficult统一设置为0.

代码实现:

  1. import json
  2. import numpy as np
  3. import cv2
  4. our_category = ['BG', 'single', 'dashed', 'double', 'arrow', 'stop', 'crosswalk']
  5. with open('./data/annotations/json/train_data.json', 'r', encoding="utf-8") as file:
  6. json_data = json.load(file)
  7. for ann in json_data["annotations"]:
  8. category_id = ann["category_id"]
  9. category = our_category[category_id]
  10. image_id = ann["image_id"]
  11. ann_id = ann["id"]
  12. for img_file in json_data["images"]:
  13. if img_file["id"] == image_id:
  14. img_file_name = img_file["file_name"]
  15. seg_info = ann["segmentation"][0]
  16. length = len(seg_info)
  17. contours = []
  18. for i in range(length):
  19. if i % 2 == 0:
  20. contours.append([seg_info[i], seg_info[i+1]])
  21. contours = np.array(contours, dtype=np.float32)
  22. # 对每个轮廓点求最小外接矩形
  23. rect = cv2.minAreaRect(contours)
  24. # cv2.boxPoints可以将轮廓点转换为四个角点坐标
  25. box = cv2.boxPoints(rect)
  26. # 令四个角点坐标为顺时针
  27. startidx = box.sum(axis=1).argmin()
  28. box = np.roll(box, 4 - startidx, 0)
  29. # 在原图上画出预测的外接矩形
  30. # img_dir_path = 'data/train/'
  31. # image = cv2.imread(os.path.join(img_dir_path, img_file_name))
  32. # box = box.reshape((-1, 1, 2)).astype(np.int32)
  33. # img = cv2.polylines(image, [box], True, (0, 255, 0), 10)
  34. # cv2.imwrite('data/visual/' + str(image_id) + '_' + str(ann_id) + '.png', img)
  35. file = open('data/annotations/DOTA_txt/' + img_file_name.split(".")[0] + '.txt', 'a')
  36. for dot in box:
  37. d0 = int(dot[0])
  38. d1 = int(dot[1])
  39. file.write(str(d0))
  40. file.write(' ')
  41. file.write(str(d1))
  42. file.write(' ')
  43. file.write(category)
  44. file.write(' ')
  45. file.write('0\n')

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

闽ICP备14008679号