当前位置:   article > 正文

目标检测实例分割数据集转换:从XML和JSON到YOLOv8(txt)

目标检测实例分割数据集转换:从XML和JSON到YOLOv8(txt)

yolov8导航

        如果大家想要了解关于yolov8的其他任务和相关内容可以点击这个链接,我这边整理了许多其他任务的说明博文,后续也会持续更新,包括yolov8模型优化、sam等等的相关内容。

YOLOv8(附带各种任务详细说明链接)

源码下载地址:

XML&JSON 目标检测、实例分割标签转换给yolo用脚本

引言

        在计算机视觉领域,目标检测是一个重要而复杂的任务。随着深度学习技术的发展,各种高效的算法和模型如YOLOv8不断涌现。然而,在使用这些先进模型之前,必须确保我们的数据集是正确格式化的。今天,我将分享一段Python代码,它能够将XML和JSON格式的标注文件转换为适合YOLOv8模型训练的格式。

数据集转换的重要性

        在目标检测任务中,我们通常有两种常见的标注格式:XML和JSON。而YOLOv8需要的是一种特定格式的文本文件,其中包含了目标的类别和位置信息。因此,将现有的标注文件转换为YOLO格式是实施有效训练的第一步。

源码

        这段代码大体包含两个功能,可以转换xml、json格式的目标检测以及实例分割任务的标签,填写的时候需要根据要求填写标签所在的路径:

  1. import json
  2. import pandas as pd
  3. import xml.etree.ElementTree as ET
  4. import os, cv2
  5. import numpy as np
  6. import glob
  7. classes = []
  8. def convert(size, box):
  9. dw = 1. / (size[0])
  10. dh = 1. / (size[1])
  11. x = (box[0] + box[1]) / 2.0 - 1
  12. y = (box[2] + box[3]) / 2.0 - 1
  13. w = box[1] - box[0]
  14. h = box[3] - box[2]
  15. x = x * dw
  16. w = w * dw
  17. y = y * dh
  18. h = h * dh
  19. return (x, y, w, h)
  20. def convert_annotation(xmlpath, xmlname):
  21. with open(xmlpath, "r", encoding='utf-8') as in_file:
  22. txtname = xmlname[:-4] + '.txt'
  23. txtfile = os.path.join(txtpath, txtname)
  24. tree = ET.parse(in_file)
  25. root = tree.getroot()
  26. filename = root.find('filename')
  27. img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
  28. h, w = img.shape[:2]
  29. res = []
  30. for obj in root.iter('object'):
  31. cls = obj.find('name').text
  32. if cls not in classes:
  33. classes.append(cls)
  34. cls_id = classes.index(cls)
  35. xmlbox = obj.find('bndbox')
  36. b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  37. float(xmlbox.find('ymax').text))
  38. bb = convert((w, h), b)
  39. res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
  40. if len(res) != 0:
  41. with open(txtfile, 'w+') as f:
  42. f.write('\n'.join(res))
  43. def query_json_to_txt(dir_json, dir_txt):
  44. classes2id = {}
  45. num = 0
  46. jsons = os.listdir(dir_json)
  47. for i in jsons:
  48. json_path = os.path.join(dir_json, i)
  49. with open(json_path, 'r', encoding="utf-8") as f:
  50. json_data = json.load(f)
  51. # print(json_data['shapes'])
  52. for j in json_data['shapes']:
  53. if j['label'] not in classes2id:
  54. classes2id[j['label']] = num
  55. num += 1
  56. def json2txt(path_json, path_txt): # 可修改生成格式
  57. with open(path_json, 'r', encoding='utf-8') as path_json:
  58. jsonx = json.load(path_json)
  59. with open(path_txt, 'w+') as ftxt:
  60. shapes = jsonx['shapes']
  61. # 获取图片长和宽
  62. width = jsonx['imageWidth']
  63. height = jsonx['imageHeight']
  64. # print(shapes)
  65. cat = shapes[0]['label']
  66. cat = classes2id[cat]
  67. for shape in shapes:
  68. # 获取矩形框两个角点坐标
  69. x1 = shape['points'][0][0]
  70. y1 = shape['points'][0][1]
  71. x2 = shape['points'][1][0]
  72. y2 = shape['points'][1][1]
  73. dw = 1. / width
  74. dh = 1. / height
  75. x = dw * (x1 + x2) / 2
  76. y = dh * (y1 + y2) / 2
  77. w = dw * abs(x2 - x1)
  78. h = dh * abs(y2 - y1)
  79. yolo = f"{cat} {x} {y} {w} {h} \n"
  80. ftxt.writelines(yolo)
  81. list_json = os.listdir(dir_json)
  82. for cnt, json_name in enumerate(list_json):
  83. if os.path.splitext(json_name)[-1] == ".json":
  84. path_json = dir_json + json_name
  85. path_txt = dir_txt + json_name.replace('.json', '.txt')
  86. json2txt(path_json, path_txt)
  87. pd.DataFrame([{"原始类别": k, "编码": v} for k,v in classes2id.items()]).to_excel("label_codes.xlsx", index=None)
  88. ###################### 实例分割处理 #######################################
  89. def parse_json_for_instance_segmentation(json_path, label_dict={}):
  90. # 打开并读取JSON文件
  91. with open(json_path, 'r', encoding='utf-8') as file:
  92. json_info = json.load(file)
  93. annotations = [] # 初始化一个用于存储注释的列表
  94. # 遍历JSON文件中的每个形状(shape)
  95. for shape in json_info["shapes"]:
  96. label = shape["label"] # 获取实例分割类别的标签
  97. # 如果标签在标签字典中 则直接编码
  98. if label in label_dict:
  99. label_dict[label] = label_dict[label] # 为该标签分配一个编码
  100. # 如果不在标签中
  101. else:
  102. next_label_code = max(label_dict.values(), default=-1) + 1
  103. label_dict[label] = next_label_code
  104. cat = label_dict[label] # 获取该标签对应的编码
  105. points = shape["points"] # 获取形状的点
  106. # 将点转换为字符串格式,并按照图像的宽度和高度进行归一化
  107. points_str = ' '.join([f"{round(point[0]/json_info['imageWidth'], 6)} {round(point[1]/json_info['imageHeight'], 6)}" for point in points])
  108. annotation_str = f"{cat} {points_str}\n" # 将编码和点字符串合并为一行注释
  109. annotations.append(annotation_str) # 将该注释添加到列表中
  110. return annotations, label_dict # 返回注释列表和更新后的标签字典
  111. def process_directory_for_instance_segmentation(json_dir, txt_save_dir, label_dict=None):
  112. if not os.path.exists(txt_save_dir):
  113. os.makedirs(txt_save_dir)
  114. # 如果没有提供初始的label_dict,则从空字典开始
  115. final_label_dict = label_dict.copy() if label_dict is not None else {}
  116. json_files = [f for f in os.listdir(json_dir) if f.endswith(".json")]
  117. for json_file in json_files:
  118. json_path = os.path.join(json_dir, json_file)
  119. txt_path = os.path.join(txt_save_dir, json_file.replace(".json", ".txt"))
  120. # 每次解析时传递当前的final_label_dict
  121. annotations, updated_label_dict = parse_json_for_instance_segmentation(json_path, final_label_dict)
  122. # 更新final_label_dict,确保包括所有新标签及其编码
  123. final_label_dict.update(updated_label_dict)
  124. # 检查annotations是否为空,如果为空则跳过写入操作
  125. if annotations:
  126. with open(txt_path, "w") as file:
  127. file.writelines(annotations)
  128. # 保存最终的标签字典
  129. pd.DataFrame(list(final_label_dict.items()), columns=['原始Label', '编码后Label']).to_excel('label_codes.xlsx', index=False)
  130. return final_label_dict
  131. # 传入参数为 实例分割 和 目标检测
  132. query_type = "目标检测"
  133. # 传入原始标签数据,比如xml、json格式文件所在的目录下
  134. label_directory = './query_data/xy/Annotations/'
  135. # 填写想转换的txt输出到哪里
  136. output_directory = './query_data/xy/txt/'
  137. anno_files = glob.glob(label_directory + "*")
  138. file_type = anno_files[0].split(".")[-1]
  139. label_dict = {
  140. # 如果想预设标签就在这里填入对应的键值对
  141. }
  142. if query_type == "实例分割":
  143. process_directory_for_instance_segmentation(label_directory, output_directory, label_dict)
  144. elif query_type == "目标检测":
  145. if file_type == "json":
  146. query_json_to_txt(label_directory, output_directory)
  147. ## 处理xml格式文件
  148. elif file_type == "xml" or file_type == "XML":
  149. postfix = 'jpg'
  150. imgpath = 'query_data/xy/images'
  151. xmlpath = 'query_data/xy/Annotations'
  152. txtpath = 'query_data/xy/txt'
  153. if not os.path.exists(txtpath):
  154. os.makedirs(txtpath, exist_ok=True)
  155. file_list = glob.glob(xmlpath + "/*")
  156. error_file_list = []
  157. for i in range(0, len(file_list)):
  158. try:
  159. path = file_list[i]
  160. if ('.xml' in path) or ('.XML' in path):
  161. convert_annotation(path, path.split("\\")[-1])
  162. print(f'file {list[i]} convert success.')
  163. else:
  164. print(f'file {list[i]} is not xml format.')
  165. except Exception as e:
  166. print(f'file {list[i]} convert error.')
  167. print(f'error message:\n{e}')
  168. error_file_list.append(list[i])
  169. print(f'this file convert failure\n{error_file_list}')
  170. print(f'Dataset Classes:{classes}')

脚本功能解析

处理XML文件

        XML格式广泛用于多种图像标注工具中。我们的脚本首先解析XML文件,提取出其中的目标类别和边界框信息。然后,这些信息被转换为YOLO格式,并保存在相应的.txt文件中。

处理JSON文件

        JSON格式也是一种常见的标注格式,尤其在实例分割任务中。脚本中包含的函数query_json_to_txt能够处理这些JSON文件,将它们转换为YOLO格式,并生成一个包含类别名称和编号的映射表。

实例分割数据处理

        对于实例分割任务,我们的脚本还提供了解析JSON文件的功能,提取出多边形的坐标信息,并转换为YOLO格式。

使用指南

要使用此脚本,您只需按照如下步骤操作:

  1. 确定您的数据集类型(目标检测或实例分割)。
  2. 准备您的XML或JSON标注文件。
  3. 运行脚本进行转换。
  4. 使用生成的文本文件训练您的YOLOv8模型。

结语

        数据预处理是机器学习项目中至关重要的一步。通过本文介绍的脚本,您可以轻松地将XML和JSON格式的标注文件转换为适合YOLOv8模型的格式。这不仅节省了大量时间,也为实现高效的目标检测任务奠定了基础。如果有哪里写的不够清晰,小伙伴本可以给评论或者留言,我这边会尽快的优化博文内容,另外如有需要,我这边可支持技术答疑与支持。

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

闽ICP备14008679号