当前位置:   article > 正文

【实例分割】转换YOLO格式标注至COCO格式JSON_yolo转coco

yolo转coco

yolo2coco代码:

  1. import json
  2. import glob
  3. import os
  4. import cv2
  5. import matplotlib.pyplot as plt
  6. from matplotlib.patches import Polygon
  7. from PIL import Image, ImageDraw, ImageFont
  8. import numpy as np
  9. def calculate_polygon_area(polygon):
  10. x = polygon[:, 0]
  11. y = polygon[:, 1]
  12. return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
  13. def calculate_bounding_box(polygon):
  14. x_min = np.min(polygon[:, 0])
  15. y_min = np.min(polygon[:, 1])
  16. x_max = np.max(polygon[:, 0])
  17. y_max = np.max(polygon[:, 1])
  18. width = x_max - x_min
  19. height = y_max - y_min
  20. return [x_min, y_min, width, height]
  21. def text_to_json_segmentation(in_labels, in_images, out_json):
  22. """
  23. Convert instance segmentation dataset from text files generated by the function 'json_to_text_segmentation'
  24. (for YOLO) to a JSON file (for MMdet). This can be applied for Level 0/1/2 (must modify the last code)
  25. :param in_labels: input folder containing the label text files
  26. :param in_images: input folder containing the image files (just for getting the image size)
  27. :param out_json: output JSON file
  28. """
  29. # Initialize the output JSON file
  30. data = dict()
  31. data['annotations'] = []
  32. data['images'] = []
  33. # Initial the number of annotations
  34. num_annotations = 1 # index starts from 1
  35. # Process the text files
  36. txt_files = glob.glob(in_labels + '/*.txt')
  37. for k in range(len(txt_files)):
  38. # Read the image to get image width and height
  39. img = Image.open(in_images + '/' + os.path.basename(txt_files[k]).replace('txt', 'jpg'))
  40. image_width, image_height = img.size
  41. # Creates annotation items of the image and append them to the list
  42. with open(txt_files[k]) as f:
  43. for line in f:
  44. # Get annotation information of each line in the text file
  45. line = [float(x) for x in line.strip().split()]
  46. class_id = int(line[0]) + 1 # index starts from 1
  47. coordinates = line[1:]
  48. polygon = np.array(coordinates).reshape(-1, 2)
  49. polygon[:, 0] = polygon[:, 0] * image_width
  50. polygon[:, 1] = polygon[:, 1] * image_height
  51. area = calculate_polygon_area(polygon)
  52. bbox = calculate_bounding_box(polygon)
  53. # Create a new annotation item
  54. ann_item = dict()
  55. ann_item['segmentation'] = [polygon.flatten().tolist()]
  56. ann_item['area'] = area
  57. ann_item['iscrowd'] = 0
  58. ann_item['image_id'] = k + 1 # index starts from 1
  59. ann_item['bbox'] = bbox
  60. ann_item['category_id'] = class_id
  61. ann_item['id'] = num_annotations
  62. data['annotations'].append(ann_item)
  63. num_annotations += 1
  64. # Create a new image item and append it to the list
  65. img_item = dict()
  66. img_item['id'] = k + 1 # index starts from 1
  67. img_item['file_name'] = os.path.basename(txt_files[k]).replace('txt', 'jpg')
  68. img_item['height'] = image_height
  69. img_item['width'] = image_width
  70. data['images'].append(img_item)
  71. print(os.path.basename(txt_files[k]) + ' done')
  72. data['categories'] = [{'supercategory': 'class1', 'id': 1, 'name': 'class1'}]
  73. # Write the dictionary to a JSON file
  74. print('Writing the data to a JSON file')
  75. with open(out_json, 'w') as f:
  76. # json.dump(data, f, cls=NpEncoder)
  77. # f.write(json.dumps(data, cls=NpEncoder, indent=4))
  78. f.write(json.dumps(data, default=int, indent=4))
  79. if __name__ == '__main__':
  80. # Convert the segmentation text files to JSON
  81. text_to_json_segmentation(in_labels='labels/test',
  82. in_images='images/test',
  83. out_json='instances_test2017.json')

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号