当前位置:   article > 正文

把labelme格式转化成yolov8支持的数据集格式_使用labelme标注后转化为yolov8

使用labelme标注后转化为yolov8

源码分享

  1. import base64
  2. import random
  3. import shutil
  4. from tqdm import tqdm
  5. import math
  6. import json
  7. import os
  8. import numpy as np
  9. import PIL.Image
  10. import PIL.ImageDraw
  11. import cv2
  12. class ConvertManager(object):
  13. def __init__(self):
  14. pass
  15. def base64_to_numpy(self, img_bs64):
  16. img_bs64 = base64.b64decode(img_bs64)
  17. img_array = np.frombuffer(img_bs64, np.uint8)
  18. cv2_img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
  19. return cv2_img
  20. @classmethod
  21. def load_labels(cls, name_file):
  22. '''
  23. load names from file.one name one line
  24. :param name_file:
  25. :return:
  26. '''
  27. with open(name_file, 'r') as f:
  28. lines = f.read().rstrip('\n').split('\n')
  29. return lines
  30. def get_class_names_from_all_json(self, json_dir):
  31. classnames = []
  32. for file in os.listdir(json_dir):
  33. if not file.endswith('.json'):
  34. continue
  35. with open(os.path.join(json_dir, file), 'r', encoding='utf-8') as f:
  36. data_dict = json.load(f)
  37. for shape in data_dict['shapes']:
  38. if not shape['label'] in classnames:
  39. classnames.append(shape['label'])
  40. return classnames
  41. def create_save_dir(self, save_dir):
  42. images_dir = os.path.join(save_dir, 'images')
  43. labels_dir = os.path.join(save_dir, 'labels')
  44. if not os.path.exists(save_dir):
  45. os.makedirs(save_dir)
  46. os.mkdir(images_dir)
  47. os.mkdir(labels_dir)
  48. else:
  49. if not os.path.exists(images_dir):
  50. os.mkdir(images_dir)
  51. if not os.path.exists(labels_dir):
  52. os.mkdir(labels_dir)
  53. return images_dir + os.sep, labels_dir + os.sep
  54. def save_list(self, data_list, save_file):
  55. with open(save_file, 'w') as f:
  56. f.write('\n'.join(data_list))
  57. def __rectangle_points_to_polygon(self, points):
  58. xmin = 0
  59. ymin = 0
  60. xmax = 0
  61. ymax = 0
  62. if points[0][0] > points[1][0]:
  63. xmax = points[0][0]
  64. ymax = points[0][1]
  65. xmin = points[1][0]
  66. ymin = points[1][1]
  67. else:
  68. xmax = points[1][0]
  69. ymax = points[1][1]
  70. xmin = points[0][0]
  71. ymin = points[0][1]
  72. return [[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]
  73. def convert_dataset(self, json_dir, json_list, images_dir, labels_dir, names, save_mode='train'):
  74. images_dir = os.path.join(images_dir, save_mode)+os.sep
  75. labels_dir = os.path.join(labels_dir, save_mode)+os.sep
  76. if not os.path.exists(images_dir):
  77. os.mkdir(images_dir)
  78. if not os.path.exists(labels_dir):
  79. os.mkdir(labels_dir)
  80. for file in tqdm(json_list):
  81. with open(os.path.join(json_dir, file), 'r', encoding='utf-8') as f:
  82. data_dict = json.load(f)
  83. image_file = os.path.join(json_dir, os.path.basename(data_dict['imagePath']))
  84. if os.path.exists(image_file):
  85. shutil.copyfile(image_file, images_dir + os.path.basename(image_file))
  86. else:
  87. imageData = data_dict.get('imageData')
  88. if not imageData:
  89. imageData = base64.b64encode(imageData).decode('utf-8')
  90. img = self.img_b64_to_arr(imageData)
  91. PIL.Image.fromarray(img).save(images_dir + file[:-4] + 'png')
  92. # convert to txt
  93. width = data_dict['imageWidth']
  94. height = data_dict['imageHeight']
  95. line_list = []
  96. for shape in data_dict['shapes']:
  97. data_list = []
  98. data_list.append(str(names.index(shape['label'])))
  99. if shape['shape_type'] == 'rectangle':
  100. points = self.__rectangle_points_to_polygon(shape['points'])
  101. for point in points:
  102. data_list.append(str(point[0] / width))
  103. data_list.append(str(point[1] / height))
  104. elif shape['shape_type'] == 'polygon':
  105. points = shape['points']
  106. for point in points:
  107. data_list.append(str(point[0] / width))
  108. data_list.append(str(point[1] / height))
  109. line_list.append(' '.join(data_list))
  110. self.save_list(line_list, labels_dir + file[:-4] + "txt")
  111. def split_train_val_test_dataset(self, file_list, train_ratio=0.9, trainval_ratio=0.9, need_test_dataset=False,
  112. shuffle_list=True):
  113. if shuffle_list:
  114. random.shuffle(file_list)
  115. total_file_count = len(file_list)
  116. train_list = []
  117. val_list = []
  118. test_list = []
  119. if need_test_dataset:
  120. trainval_count = int(total_file_count * trainval_ratio)
  121. trainval_list = file_list[:trainval_count]
  122. test_list = file_list[trainval_count:]
  123. train_count = int(train_ratio * len(trainval_list))
  124. train_list = trainval_list[:train_count]
  125. val_list = trainval_list[train_count:]
  126. else:
  127. train_count = int(train_ratio * total_file_count)
  128. train_list = file_list[:train_count]
  129. val_list = file_list[train_count:]
  130. return train_list, val_list, test_list
  131. def start(self, json_dir, save_dir, names=None, train_ratio=0.9):
  132. images_dir, labels_dir = self.create_save_dir(save_dir)
  133. if names is None or len(names) == 0:
  134. print('class names will load from all json file')
  135. names = self.get_class_names_from_all_json(json_dir)
  136. print('find {} class names :'.format(len(names)), names)
  137. if len(names) == 0:
  138. return
  139. self.save_list(names, os.path.join(save_dir, 'labels.txt'))
  140. print('start convert')
  141. all_json_list = []
  142. for file in os.listdir(json_dir):
  143. if not file.endswith('.json'):
  144. continue
  145. all_json_list.append(file)
  146. train_list, val_list, test_list = self.split_train_val_test_dataset(all_json_list, train_ratio)
  147. self.convert_dataset(json_dir, train_list, images_dir, labels_dir, names, 'train')
  148. self.convert_dataset(json_dir, val_list, images_dir, labels_dir, names, 'val')
  149. if __name__ == '__main__':
  150. cm = ConvertManager()
  151. cm.start(r'D:\torch1\yolov8-ultralytics-main\tomatoimg_jsonjpg', r'D:\torch1\yolov8-ultralytics-main\mydata')

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

闽ICP备14008679号