当前位置:   article > 正文

Yolov8训练自己数据集_yolov8训练自己的txt文件代码

yolov8训练自己的txt文件代码

Ultralytics YOLOv8.0.202

 Python-3.9.16

torch-1.13.1

CUDA:11.6 (NVIDIA GeForce GTX 1650, 4096MiB)

我自己数据集是xml格式

将PascalVOC格式的XML标注文件转换为YOLO格式的TXT标注文件,转换代码

  1. import xml.etree.ElementTree as ET
  2. import os, cv2
  3. import numpy as np
  4. from os import listdir
  5. from os.path import join
  6. classes = []
  7. def convert(size, box):
  8. dw = 1. / (size[0])
  9. dh = 1. / (size[1])
  10. x = (box[0] + box[1]) / 2.0 - 1
  11. y = (box[2] + box[3]) / 2.0 - 1
  12. w = box[1] - box[0]
  13. h = box[3] - box[2]
  14. x = x * dw
  15. w = w * dw
  16. y = y * dh
  17. h = h * dh
  18. return (x, y, w, h)
  19. def convert_annotation(xmlpath, xmlname):
  20. with open(xmlpath, "r", encoding='utf-8') as in_file:
  21. txtname = xmlname[:-4] + '.txt'
  22. txtfile = os.path.join(txtpath, txtname)
  23. tree = ET.parse(in_file)
  24. root = tree.getroot()
  25. filename = root.find('filename')
  26. img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
  27. h, w = img.shape[:2]
  28. res = []
  29. for obj in root.iter('object'):
  30. cls = obj.find('name').text
  31. if cls not in classes:
  32. classes.append(cls)
  33. cls_id = classes.index(cls)
  34. xmlbox = obj.find('bndbox')
  35. b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  36. float(xmlbox.find('ymax').text))
  37. bb = convert((w, h), b)
  38. res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
  39. if len(res) != 0:
  40. with open(txtfile, 'w+') as f:
  41. f.write('\n'.join(res))
  42. if __name__ == "__main__":
  43. postfix = 'jpg'
  44. imgpath = 'VOCdevkit/JPEGImages'
  45. xmlpath = 'VOCdevkit/Annotations'
  46. txtpath = 'VOCdevkit/txt'
  47. if not os.path.exists(txtpath):
  48. os.makedirs(txtpath, exist_ok=True)
  49. list = os.listdir(xmlpath)
  50. error_file_list = []
  51. for i in range(0, len(list)):
  52. try:
  53. path = os.path.join(xmlpath, list[i])
  54. if ('.xml' in path) or ('.XML' in path):
  55. convert_annotation(path, list[i])
  56. print(f'file {list[i]} convert success.')
  57. else:
  58. print(f'file {list[i]} is not xml format.')
  59. except Exception as e:
  60. print(f'file {list[i]} convert error.')
  61. print(f'error message:\n{e}')
  62. error_file_list.append(list[i])
  63. print(f'this file convert failure\n{error_file_list}')
  64. print(f'Dataset Classes:{classes}')

注意修改文件的路径

将images中的图片换成自己数据集的图片,图片存放于images/train,我只用的train,没有用test和val,所以只说train的。

将xml转换成的txt直接转换到labels/train文件夹里面。

一切就绪,开始训练。

我觉得用以上方法比用下面这个xml训练要方便,之前用VOC训练的时候一直报错啊,改了之后训练成功了,因人而异吧也算是。

报错过程:

自己的数据集训练过程。

记录自己训练过程,如果在训练其他的会再记录。

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

闽ICP备14008679号