{"id":13642912,"url":"https://github.com/DataXujing/YOLOv6","last_synced_at":"2025-04-20T21:32:11.796Z","repository":{"id":41276581,"uuid":"508975677","full_name":"DataXujing/YOLOv6","owner":"DataXujing","description":":cyclone: :cyclone: 手摸手 美团 YOLOv6模型训练和TensorRT端到端部署方案教程","archived":false,"fork":false,"pushed_at":"2022-06-30T07:49:39.000Z","size":27058,"stargazers_count":28,"open_issues_count":0,"forks_count":6,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-08-02T01:17:38.438Z","etag":null,"topics":["mt-yolov6","tensorrt","yolov6"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DataXujing.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-06-30T07:22:13.000Z","updated_at":"2024-07-19T03:06:27.000Z","dependencies_parsed_at":"2022-07-13T15:29:46.021Z","dependency_job_id":null,"html_url":"https://github.com/DataXujing/YOLOv6","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FYOLOv6","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FYOLOv6/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FYOLOv6/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DataXujing%2FYOLOv6/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DataXujing","download_url":"https://codeload.github.com/DataXujing/YOLOv6/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223839148,"owners_count":17211881,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mt-yolov6","tensorrt","yolov6"],"created_at":"2024-08-02T01:01:37.974Z","updated_at":"2025-04-20T21:32:11.789Z","avatar_url":"https://github.com/DataXujing.png","language":"Python","funding_links":[],"categories":["Other Versions of YOLO"],"sub_categories":[],"readme":"## YOLOv6 训练自己的数据集（包括端到端的TensorRT模型加速）\n\n适用版本：0.1.0 (目前美团并未开源大模型)\n\n最近美团的视觉智能部开源了MT-YOLOv6 (YOLOv6),致力于工业应用。框架同时专注于检测的精度和推理效率，在工业界常用的尺寸模型中：YOLOv6-nano 在 COCO 上精度可达 35.0% AP，在 T4 上推理速度可达 1242 FPS；YOLOv6-s 在 COCO 上精度可达 43.1% AP，在 T4 上推理速度可达 520 FPS。在部署方面，YOLOv6 支持 GPU（TensorRT）、CPU（OPENVINO）、ARM（MNN、TNN、NCNN）等不同平台的部署，极大地简化工程部署时的适配工作。\n\n关于YOLOv6的模型结构介绍可以参考： [【YOLOv6：又快又准的目标检测框架开源啦】](https://mp.weixin.qq.com/s/RrQCP4pTSwpTmSgvly9evg)\n\n\u003cimg src=\"assets/picture.png\" width=\"800\"\u003e\n\n下面以YOLOv6s的训练和测试过程为例，详细手摸手基于YOLOv6训练自己的数据集并进行TensorRT模型加速推断！\n\n\n### 1.训练环境搭建\n\n```\n#python 3.8\n# pytorch \u003e= 1.8.0\n# torchvision \u003e= 0.9.0\n\npip3 install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/\n```\n\n\n### 2.数据准备\n\n研究过YOLOv5的应该知道，YOLOv6支持YOLOv5的数据格式，可以参考\u003chttps://github.com/DataXujing/YOLO-v5\u003e\n\n1. 可以使用LabelImg,Labelme,Labelbox, CVAT等来标注数据，对于目标检测而言需要标注bounding box即可。然后需要将标注转换为和darknet format相同的标注形式，每一个图像生成一个`*.txt`的标注文件（如果该图像没有标注目标则不用创建`*.txt`文件）。创建的`*.txt`文件遵循如下规则：\n\n+ 每一行存放一个标注类别\n+ 每一行的内容包括class x_center y_center width height\n+ Bounding box 的坐标信息是归一化之后的（0-1）\n+ class label转化为index时计数是从0开始的\n\n```python\ndef convert(size, box):\n    '''\n    将标注的xml文件标注转换为darknet形的坐标\n    '''\n    dw = 1./(size[0])\n    dh = 1./(size[1])\n    x = (box[0] + box[1])/2.0 - 1\n    y = (box[2] + box[3])/2.0 - 1\n    w = box[1] - box[0]\n    h = box[3] - box[2]\n    x = x*dw\n    w = w*dw\n    y = y*dh\n    h = h*dh\n    return (x,y,w,h)\n```\n每一个标注`*.txt`文件存放在和图像相似的文件目录下，只需要将`/images/*.jpg`替换为`/lables/*.txt`即可（这个在加载数据时代码内部的处理就是这样的，可以自行修改为VOC的数据格式进行加载）\n\n例如：\n\n```\ndatasets/score/images/train/000000109622.jpg  # image\ndatasets/score/labels/train/000000109622.txt  # label\n```\n\n如果一个标注文件包含5个person类别（person在coco数据集中是排在第一的类别因此index为0）：\n\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"assets/dataset_1.png\" \u003e\n\u003c/div\u003e\n\n2. 组织训练集的目录\n\n将训练集train和验证集val的images和labels文件夹按照如下的方式进行存放\n\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"assets/dataset_2.png\" \u003e\n\u003c/div\u003e\n\n3. 在`$YOLOv6/data/`下创建`dataset.yaml`(这里我们叫`score.yaml`)\n\n```yaml\ntrain: ./dataset/score/images/train # train images\nval: ./dataset/score/images/val # val images\ntest: ./dataset/score/images/test # test images (optional)\n\n# Classes\nnc: 4  # number of classes\nnames: ['person','cat','dog','horse']  # class names\n```\n至此数据准备阶段已经完成，过程中我们假设算法工程师的数据清洗和数据集的划分过程已经自行完成\n\n\u003e 注意尽量不要用纯数字作为训练数据的文件名！\n\n### 3.创建模型配置文件\n\n我们可以使用模型配置文件指定模型结构的配置，训练的超参数，优化器，数据增强等；把模型的配置文件放在`$YOLOv6/configs/yolov6s_score.py`\n\n\u003cdetails\u003e\n\u003csummary\u003e点我查看config\u003c/summary\u003e\n\n```python\n# YOLOv6s model\nmodel = dict(\n    type='YOLOv6s',\n    pretrained=\"./weights/yolov6s.pt\",\n    depth_multiple=0.33,\n    width_multiple=0.50,\n    backbone=dict(\n        type='EfficientRep',\n        num_repeats=[1, 6, 12, 18, 6],\n        out_channels=[64, 128, 256, 512, 1024],\n        ),\n    neck=dict(\n        type='RepPAN',\n        num_repeats=[12, 12, 12, 12],\n        out_channels=[256, 128, 128, 256, 256, 512],\n        ),\n    head=dict(\n        type='EffiDeHead',\n        in_channels=[128, 256, 512],\n        num_layers=3,\n        begin_indices=24,\n        anchors=1,\n        out_indices=[17, 20, 23],\n        strides=[8, 16, 32],\n        iou_type='siou'\n    )\n)\n\nsolver = dict(\n    optim='SGD',\n    lr_scheduler='Cosine',\n    lr0=0.01,\n    lrf=0.01,\n    momentum=0.937,\n    weight_decay=0.0005,\n    warmup_epochs=3.0,\n    warmup_momentum=0.8,\n    warmup_bias_lr=0.1\n)\n\ndata_aug = dict(\n    hsv_h=0.015,\n    hsv_s=0.7,\n    hsv_v=0.4,\n    degrees=0.0,\n    translate=0.1,\n    scale=0.5,\n    shear=0.0,\n    flipud=0.0,\n    fliplr=0.5,\n    mosaic=1.0,\n    mixup=0.0,\n)\n```\n\n\u003c/details\u003e\n\n\n### 4.模型训练(Train)\n\n+ 单GPU\n\n```shell\npython tools/train.py --workers 4 --batch 128 --conf configs/yolov6s_score.py --data data/score.yaml --device 0\n```\n\n+ 多GPU\n\n```shell\npython -m torch.distributed.launch --nproc_per_node 2 tools/train.py --batch 256 --conf configs/yolov6s_score.py --data data/score.yaml --device 0,1\n```\n\n### 5.模型eval和inference\n\n+ Eval\n\n```shell\npython tools/eval.py --data data/score.yaml  --weights runs/train/exp/weights/last_ckpt.pt --device 0\n```\n+ Inference\n\n```shell\npython inference.py\n#python tools/infer.py --weights output_dir/name/weights/best_ckpt.pt --source img.jpg --device 0\n```\n\u003cdiv align=center\u003e\n\n|                                 |                                  |                                  |                                  \n| :-----------------------------: | :------------------------------: | :------------------------------: | \n| \u003cimg src=\"assets/image1.jpg\"  height=270 width=270\u003e | \u003cimg src=\"assets/image2.jpg\" width=270 height=270\u003e | \u003cimg src=\"assets/image3.jpg\" width=270 height=270\u003e |  \n\n\u003c/div\u003e\n\n### 6.TensorRT 模型加速(C++)\n\n我们实现了完全端到端的YOLOv6的tensorRT推断加速，将TensorRT NMS Plugin加入到模型结构实现端到端的推断！\n\n1. 导出ONNX\n\nYOLOv6引入了 [RepVGG](https://arxiv.org/pdf/2101.03697) style 结构，RepVGG Style 结构是一种在训练时具有多分支拓扑，而在实际部署时可以等效融合为单个 `3x3` 卷积的一种可重参数化的结构（融合过程如下图所示）。通过融合成的 `3x3` 卷积结构，可以有效利用计算密集型硬件计算能力（比如 GPU），同时也可获得 GPU/CPU 上已经高度优化的 NVIDIA cuDNN 和 Intel MKL 编译框架的帮助。\n实验表明，通过上述策略，YOLOv6 减少了在硬件上的延时，并显著提升了算法的精度，让检测网络更快更强。以 nano 尺寸模型为例，对比 YOLOv5-nano 采用的网络结构，本方法在速度上提升了21%，同时精度提升 3.6% AP。\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"assets/trt_1.png\" \u003e\n\u003c/div\u003e\n\n导出ONNX的过程，`layer.switch_to_deploy()`即完成了上述操作\n\n```shell\npython deploy/ONNX/export_onnx.py --weights runs/train/exp/weights/last_ckpt.pt  --device 0\n```\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"assets/onnx1.png\" \u003e\n\u003c/div\u003e\n\n1. 增加NMS Plugin结点\n\n\n需要在`YOLOv6s.onnx`后拼接下面的结点\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"assets/onnx2.png\" \u003e\n\u003c/div\u003e\n\n可执行如下代码：\n\n```shell\n\npython tensorrt/yolov6_add_postprocess.py\npython tensorrt/yolov6_add_nms.py\n\n```\n\n\n2. 序列化Engine\n\n```shell\ntrtexec --onnx=best_ckpt_1_nms.onnx --saveEngine=yolov6.engine --workspace=3000 --verbose\n\n```\n\n3. 推断测试\n\n+ 前处理的过程\n\n1. OpenCV加载图像\n2. letterbox实现\n   \n    + `r=min(640/image_width, 640/image_height)`:取缩放比最小的边的缩放比例\n    + padding\n\n        - `pad_w=(640-image_width*r)/2`;`pad_h=(640-image_height*r)/2`\n\n        - 图像缩放： `interpolation=cv2.INTER_LINEAR`,缩放为`(image_width*r,image_height*r)`\n        - 上下填充`pad_h`,左右填充为`pad_w`,填充的像素值为`(114,114,114)`\n3. HWC转CHW,BGR转RGB\n4. 归一化：逐像素除以255.0\n\n不难发现图像前处理和YOLOv5基本相同。\n\n其C++的实现如下：\n\n```c++\nvoid preprocess(cv::Mat\u0026 img, float data[]) {\n\tint w, h, x, y;\n\tfloat r_w = INPUT_W / (img.cols*1.0);\n\tfloat r_h = INPUT_H / (img.rows*1.0);\n\tif (r_h \u003e r_w) {\n\t\tw = INPUT_W;\n\t\th = r_w * img.rows;\n\t\tx = 0;\n\t\ty = (INPUT_H - h) / 2;\n\t}\n\telse {\n\t\tw = r_h * img.cols;\n\t\th = INPUT_H;\n\t\tx = (INPUT_W - w) / 2;\n\t\ty = 0;\n\t}\n\tcv::Mat re(h, w, CV_8UC3);\n\tcv::resize(img, re, re.size(), 0, 0, cv::INTER_LINEAR);\n\t//cudaResize(img, re);\n\tcv::Mat out(INPUT_H, INPUT_W, CV_8UC3, cv::Scalar(114, 114, 114));\n\tre.copyTo(out(cv::Rect(x, y, re.cols, re.rows)));\n\n\tint i = 0;\n\tfor (int row = 0; row \u003c INPUT_H; ++row) {\n\t\tuchar* uc_pixel = out.data + row * out.step;\n\t\tfor (int col = 0; col \u003c INPUT_W; ++col) {\n\t\t\tdata[i] = (float)uc_pixel[2] / 255.0;\n\t\t\tdata[i + INPUT_H * INPUT_W] = (float)uc_pixel[1] / 255.0;\n\t\t\tdata[i + 2 * INPUT_H * INPUT_W] = (float)uc_pixel[0] / 255.0;\n\t\t\tuc_pixel += 3;\n\t\t\t++i;\n\t\t}\n\t}\n\n}\n\n```\n\n\n打开`tensorrt/yolov6_trt`下的VS项目，进行推断，其推断结果如下：\n\n\u003cdiv align=center\u003e\n\n|                                 |                                  |                                  |                                  \n| :-----------------------------: | :------------------------------: | :------------------------------: | \n| \u003cimg src=\"assets/image1_trt.jpg\"  height=270 width=270\u003e | \u003cimg src=\"assets/image2_trt.jpg\" width=270 height=270\u003e | \u003cimg src=\"assets/image3_trt.jpg\" width=270 height=270\u003e |  \n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDataXujing%2FYOLOv6","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDataXujing%2FYOLOv6","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDataXujing%2FYOLOv6/lists"}