当前位置:   article > 正文

修改github上yolo源码实现自建数据集的目标检测任务_yolo目标检测+猫狗大战

yolo目标检测+猫狗大战

本项目自建猫狗数据集,搭建Yolov5,实现猫狗检测

一、环境搭建

1.在Anaconda中创建pytorch环境

conda create -n pytorch python=3.8

2.激活pytorch环境

conda activate pytorch

3.进入PyTorch

 复制命令,安装支持包

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

4.安装pycharmDownload PyCharm: Python IDE for Professional Developers by JetBrains

5.在pycharm中创建pytorch环境的工程项目文件

 二、数据集制作

采用labelimg进行数据集标注

1.安装labelimg

cmd中输入指令

pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple

2.创建数据集文件夹VOC2007并创建子文件

JPEGImages存放需要打标签的图片文件

Annotations存放标注的标签文件

predefined_classes.txt存放类别名称

3.在JPEGImages中放入待标注的图片,分别是猫、狗,然后在predefined_classes.txt内输入定义的类别

 

4.在cmd中进入数据集文件夹目录下打开labelimg

labelimg JPEGImages predefined_classes.txt

  在view中勾选

Auto Save mode 切换下一张图时自动保存标签

Display Labels 显示标注框和标签

Advanced Mode 标注的十字架一直悬浮在窗口

 5.开始标注

 三、VOC标签格式转YOLO格式并划分训练集和测试集

1.Yolov5训练所需要的文件格式是yolo(txt)格式的,在此对xml格式的标签文件转换为txt文件,同时训练将数据集按比例划分为训练集和验证集。(注:需要修改标签名称)

  1. import xml.etree.ElementTree as ET
  2. import pickle
  3. import os
  4. from os import listdir, getcwd
  5. from os.path import join
  6. import random
  7. from shutil import copyfile
  8. #标签名称
  9. classes = ["dog", "cat"]
  10. #80%划分给训练集,20%划分给验证集
  11. TRAIN_RATIO = 80
  12. def clear_hidden_files(path):
  13. dir_list = os.listdir(path)
  14. for i in dir_list:
  15. abspath = os.path.join(os.path.abspath(path), i)
  16. if os.path.isfile(abspath):
  17. if i.startswith("._"):
  18. os.remove(abspath)
  19. else:
  20. clear_hidden_files(abspath)
  21. def convert(size, box):
  22. dw = 1. / size[0]
  23. dh = 1. / size[1]
  24. x = (box[0] + box[1]) / 2.0
  25. y = (box[2] + box[3]) / 2.0
  26. w = box[1] - box[0]
  27. h = box[3] - box[2]
  28. x = x * dw
  29. w = w * dw
  30. y = y * dh
  31. h = h * dh
  32. return (x, y, w, h)
  33. def convert_annotation(image_id):
  34. in_file = open('VOCdevkit/VOC2007/Annotations/%s.xml' % image_id,encoding='UTF-8')
  35. out_file = open('VOCdevkit/VOC2007/YOLOLabels/%s.txt' % image_id, 'w',encoding='UTF-8')
  36. tree = ET.parse(in_file)
  37. root = tree.getroot()
  38. size = root.find('size')
  39. w = int(size.find('width').text)
  40. h = int(size.find('height').text)
  41. for obj in root.iter('object'):
  42. difficult = obj.find('difficult').text
  43. cls = obj.find('name').text
  44. if cls not in classes or int(difficult) == 1:
  45. continue
  46. cls_id = classes.index(cls)
  47. xmlbox = obj.find('bndbox')
  48. b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  49. float(xmlbox.find('ymax').text))
  50. bb = convert((w, h), b)
  51. out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
  52. in_file.close()
  53. out_file.close()
  54. wd = os.getcwd()
  55. wd = os.getcwd()
  56. data_base_dir = os.path.join(wd, "VOCdevkit/")
  57. if not os.path.isdir(data_base_dir):
  58. os.mkdir(data_base_dir)
  59. work_sapce_dir = os.path.join(data_base_dir, "VOC2007/")
  60. if not os.path.isdir(work_sapce_dir):
  61. os.mkdir(work_sapce_dir)
  62. annotation_dir = os.path.join(work_sapce_dir, "Annotations/")
  63. if not os.path.isdir(annotation_dir):
  64. os.mkdir(annotation_dir)
  65. clear_hidden_files(annotation_dir)
  66. image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
  67. if not os.path.isdir(image_dir):
  68. os.mkdir(image_dir)
  69. clear_hidden_files(image_dir)
  70. yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")
  71. if not os.path.isdir(yolo_labels_dir):
  72. os.mkdir(yolo_labels_dir)
  73. clear_hidden_files(yolo_labels_dir)
  74. yolov5_images_dir = os.path.join(data_base_dir, "images/")
  75. if not os.path.isdir(yolov5_images_dir):
  76. os.mkdir(yolov5_images_dir)
  77. clear_hidden_files(yolov5_images_dir)
  78. yolov5_labels_dir = os.path.join(data_base_dir, "labels/")
  79. if not os.path.isdir(yolov5_labels_dir):
  80. os.mkdir(yolov5_labels_dir)
  81. clear_hidden_files(yolov5_labels_dir)
  82. yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")
  83. if not os.path.isdir(yolov5_images_train_dir):
  84. os.mkdir(yolov5_images_train_dir)
  85. clear_hidden_files(yolov5_images_train_dir)
  86. yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")
  87. if not os.path.isdir(yolov5_images_test_dir):
  88. os.mkdir(yolov5_images_test_dir)
  89. clear_hidden_files(yolov5_images_test_dir)
  90. yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")
  91. if not os.path.isdir(yolov5_labels_train_dir):
  92. os.mkdir(yolov5_labels_train_dir)
  93. clear_hidden_files(yolov5_labels_train_dir)
  94. yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")
  95. if not os.path.isdir(yolov5_labels_test_dir):
  96. os.mkdir(yolov5_labels_test_dir)
  97. clear_hidden_files(yolov5_labels_test_dir)
  98. train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w')
  99. test_file = open(os.path.join(wd, "yolov5_val.txt"), 'w')
  100. train_file.close()
  101. test_file.close()
  102. train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')
  103. test_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')
  104. list_imgs = os.listdir(image_dir) # list image files
  105. prob = random.randint(1, 100)
  106. print("Probability: %d" % prob)
  107. for i in range(0, len(list_imgs)):
  108. path = os.path.join(image_dir, list_imgs[i])
  109. if os.path.isfile(path):
  110. image_path = image_dir + list_imgs[i]
  111. voc_path = list_imgs[i]
  112. (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))
  113. (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
  114. annotation_name = nameWithoutExtention + '.xml'
  115. annotation_path = os.path.join(annotation_dir, annotation_name)
  116. label_name = nameWithoutExtention + '.txt'
  117. label_path = os.path.join(yolo_labels_dir, label_name)
  118. prob = random.randint(1, 100)
  119. print("Probability: %d" % prob)
  120. if (prob < TRAIN_RATIO): # train dataset
  121. if os.path.exists(annotation_path):
  122. train_file.write(image_path + '\n')
  123. convert_annotation(nameWithoutExtention) # convert label
  124. copyfile(image_path, yolov5_images_train_dir + voc_path)
  125. copyfile(label_path, yolov5_labels_train_dir + label_name)
  126. else: # test dataset
  127. if os.path.exists(annotation_path):
  128. test_file.write(image_path + '\n')
  129. convert_annotation(nameWithoutExtention) # convert label
  130. copyfile(image_path, yolov5_images_test_dir + voc_path)
  131. copyfile(label_path, yolov5_labels_test_dir + label_name)
  132. train_file.close()
  133. test_file.close()

2.将之前做好的数据集复制到VOCdevkit-VOC2007下的Annotations和JPEGImages中

(注:运行完上述代码后,会建立空的文件,将数据集复制进去后,再次运行文件即可完成转换与划分)

 四、利用Yolov5训练目标检测模型

1.在github上下载yolov5源码

GitHub - ultralytics/yolov5 at v5.0

 

2.pycharm的命令终端中输入如下命令,安装依赖包

pip install -r requirements.txt

  3.将数据集(VOCdevkit文件)复制到工程文件中

   4.在下载预训练权重,以yolov5s.pt为例,下载后放入weights文件中

 Releases · ultralytics/yolov5 · GitHub

   5.修改data目录下的yaml文件

复制VOC.yaml文件,将复制后的文件重命名为dog_cat.yaml,之后对dog_cat.yaml中的参数进行修改(路径修改方式如下)

  6.修改models下的yaml文件

复制yolov5s.yaml文件,将复制后的文件重命名为yolo5s_dog_cat.yaml,之后对yolo5s_dog_cat.yaml中的参数进行修改

 7.修改train.py中的参数后运行train.py

(注:遇到“页面文件太小,无法完成操作”的红字不用管,只要程序在运行,等待一会就会开始训练)

可以通过如下命令查看训练参数

  1. tensorboard --logdir=runs/train # 训练过程中查看参数
  2. tensorboard --logdir=runs # 训练完查看参数

 8.训练完成后,最佳参数保存在runs-train-exp40-weights中

 9.修改detect.py中参数并运行

(注:以照片为例进行预测)

 10.检测结果保存在runs-detect-exp20中

(注:由于本实例只演示操作,数据集很少,训练轮数也很少,所以精度很低,调小detect.py中的置信度参数,如果不调可能无法框出预测结果)

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

闽ICP备14008679号