当前位置:   article > 正文

Yolov5训练自己的数据集_from models.experimental import attempt_load

from models.experimental import attempt_load

本文介绍了如果通过Yolov5框架训练自己的数据集,主要内容包括数据集格式、数据集拆分方法、描述文件修改以及训练和测试方法。

还没有搭建Yolov5环境的可以参考我上一篇博文:

Yolov5目标检测环境搭建过程(Cuda+Pytorch+Yolov5)

本文描述的所有代码均已放到Github上,感兴趣的可以直接下载:

(后续放上)

一、准备材料:图片集,标签集

1、没有标签的需要先使用labelimg工具制作标签,比较简单,具体制作方法可以参考以下链接

https://blog.csdn.net/weixin_44403922/article/details/110914740

2、标签格式转换

labelimg工具生成的标签是xml格式的,之前的目标检测框架用的都是xml格式,但是yolov5框架使用的是txt格式,所以第一步需要将xml格式的标签转换为txt格式

将xml数据标签转换为yolo所需的txt格式标签,用以下转换代码voctoyolo.py进行转换就行。

  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. def convert(size, box):
  7. x_center = (box[0] + box[1]) / 2.0
  8. y_center = (box[2] + box[3]) / 2.0
  9. x = x_center / size[0]
  10. y = y_center / size[1]
  11. w = (box[1] - box[0]) / size[0]
  12. h = (box[3] - box[2]) / size[1]
  13. return (x, y, w, h)
  14. def convert_annotation(xml_files_path, save_txt_files_path, classes):
  15. xml_files = os.listdir(xml_files_path)
  16. print(xml_files)
  17. for xml_name in xml_files:
  18. print(xml_name)
  19. xml_file = os.path.join(xml_files_path, xml_name)
  20. out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
  21. out_txt_f = open(out_txt_path, 'w')
  22. tree = ET.parse(xml_file)
  23. root = tree.getroot()
  24. size = root.find('size')
  25. w = int(size.find('width').text)
  26. h = int(size.find('height').text)
  27. for obj in root.iter('object'):
  28. difficult = obj.find('difficult').text
  29. cls = obj.find('name').text
  30. if cls not in classes or int(difficult) == 1:
  31. continue
  32. cls_id = classes.index(cls)
  33. xmlbox = obj.find('bndbox')
  34. b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
  35. float(xmlbox.find('ymax').text))
  36. # b=(xmin, xmax, ymin, ymax)
  37. print(w, h, b)
  38. bb = convert((w, h), b)
  39. out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
  40. if __name__ == "__main__":
  41. classes = ['blackgan', 'mei']
  42. # 1、voc格式的xml标签文件路径
  43. xml_files1 = r'D:\2021file\Biye\yolov5-master\VOC2007\Annotations'
  44. # 2、转化为yolo格式的txt标签文件存储路径
  45. save_txt_files1 = r'D:\2021file\Biye\yolov5-master\VOC2007\labels'
  46. convert_annotation(xml_files1, save_txt_files1, classes)

网上的有的报错:ttributeError: 'NoneType' object has no attribute 'text'

可能是因为下面这行代码(我看有的写的是Difficult,改成difficult就不报错了)

difficult = obj.find('difficult').text

生成后的标签在VOC2007/labes文件下,如下图所示:

 

 

3、手动分割训练集、测试集

将xml转换为txt后,我们对数据集进行手动分割,将图片和标签放到对应的文件夹下,文件组成如下:

注意放入文件中的images和labels要能一一对应

备注:

由于之前在yolov3训练VOC数据时会通过代码生成train、trainval、val、test四个txt描述文件,对数据集进行分割(yolov3目标检测搭建过程可以查看我另一篇博文,后续放上),所以我看网上很多教程都是先生成以上文件,然后通过以上文件再转换得到label的txt文件,但是最后发现代码并不能使用train、val,所以最后我放弃了自动分割数据集的方法,直接采用手动分割的方式。

二、描述文件修改

1、对data文件夹下的voc.yaml文件进行修改,我直接复制了副本并将文件名修改为myvoc.yaml

其中,train和val分别对应刚刚建立的放置图片的文件夹路径

nc为类别数

names中为对应的类别名称

其余内容均可删掉

2、对models文件夹下的yolov5.yaml文件进行修改(我们采用yolov5s.pt作为初始模型,在其基础上进行训练,所以要对yolov5.yaml中的参数进行修改)

只需要修改类别数即可

三、训练

1、我们对train.py中对应的路径进行修改

将yolov5s.pt、yolov5s.yaml、myvoc.yaml对应的路径修改即可

2、最后运行train.py文件开始训练,若报错内存容量不足,可将其中的batch-size修改小一点

通过tensorboard查看训练过程:

点击Terminal,输入命令

tensorboard --logdir="runs/train/exp11"

其中,runs/train/exp11自动生成的文件夹,里面保存了训练过程文件,exp11是我这里最新的文件,因为每运行一次程序都会生成一个新的文件,所以需要对runs/train查看最新的文件即为当前对应的训练文件,执行命令后点击生成的http://localhost:6006/进入浏览器查看

训练过程:

训练结果:

四、测试

训练完成后在runs\train\exp11\weights文件夹中会保存训练好的权重,一共两个,一个是最后一轮保存的,一个是训练过程中最优的一次保存的,我们选择best.pt

在detect中修改对应的权重路径:

1、测试文件夹下的所有图片

data\images\mytestdata里面是我放的测试图片,一共放了五张,程序会自动检测文件夹下的所有图片,并保存在runs\detect\exp中

2、为了方便调用,自己写了一个直接读取图片然后输出结果的代码mydetect.py

  1. from numpy import random
  2. import torch
  3. from models.experimental import attempt_load
  4. from utils.datasets import LoadStreams, LoadImages
  5. from utils.general import (
  6. check_img_size, non_max_suppression, apply_classifier, scale_coords,
  7. xyxy2xywh, strip_optimizer, set_logging)
  8. from utils.torch_utils import select_device, load_classifier
  9. import os
  10. import shutil
  11. # Initialize
  12. set_logging()
  13. device = select_device('')
  14. half = device.type != 'cpu' # half precision only supported on CUDA
  15. # Load model
  16. model = attempt_load('models/yolov5s.pt', map_location=device) # load FP32 model
  17. imgsz = check_img_size(512, s=model.stride.max()) # check img_size
  18. if half:
  19. model.half() # to FP16
  20. # Get names and colors
  21. names = model.module.names if hasattr(model, 'module') else model.names
  22. colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  23. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  24. _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
  25. def PoseDect(path, imgsz=512):
  26. res = []
  27. dataset = LoadImages(path, img_size=imgsz)
  28. for path, img, im0s, vid_cap in dataset:
  29. img = torch.from_numpy(img).to(device)
  30. img = img.half() if half else img.float() # uint8 to fp16/32
  31. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  32. if img.ndimension() == 3:
  33. img = img.unsqueeze(0)
  34. # Inference
  35. #t1 = time_synchronized()
  36. pred = model(img, augment=False)[0]
  37. # Apply NMS
  38. pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)
  39. # Process detections
  40. for i, det in enumerate(pred): # detections per image
  41. gn = torch.tensor(im0s.shape)[[1, 0, 1, 0]] # normalization gain whwh
  42. if det is not None and len(det):
  43. # Rescale boxes from img_size to im0 size
  44. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0s.shape).round()
  45. for *xyxy, conf, cls in reversed(det):
  46. x, y, w, h = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
  47. res.append([names[int(cls)], float(conf), x, y, w, h])
  48. return res
  49. if __name__ == '__main__':
  50. path = r'D:\2021file\Biye\yolov5-master\data\images\bus.jpg'
  51. s = PoseDect(path=path)
  52. print(s)
  53. import cv2
  54. img = cv2.imread(r'D:\2021file\Biye\yolov5-master\data\images\bus.jpg')
  55. for box in s:
  56. cla,p=box[:2]
  57. x1, y1, x2, y2 = box[2:]
  58. # 映射原图尺寸
  59. x = int(x1 * img.shape[1])
  60. y = int(y1 * img.shape[0])
  61. w = int(x2 * img.shape[1])
  62. h = int(y2 * img.shape[0])
  63. # 计算出左上角和右下角:原x,y是矩形框的中心点
  64. a = int(x - w / 2)
  65. b = int(y - h / 2)
  66. c = int(x + w / 2)
  67. d = int(y + h / 2)
  68. print(x1, y1, x1 + x2, y1 + y2)
  69. print(x, y, x + w, y + h)
  70. print(a, b, c, d)
  71. cv2.rectangle(img, (a, b), (c, d), (255, 0, 0), 2)
  72. cv2.putText(img, cla+":"+str(round(p, 2)), (a+5, b+20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255,0), 1)
  73. cv2.imshow('dst', img)
  74. cv2.waitKey()
  75. cv2.destroyAllWindows()

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

闽ICP备14008679号