{"id":15034465,"url":"https://github.com/peterh0323/smart_construction","last_synced_at":"2025-05-15T10:05:47.056Z","repository":{"id":37395555,"uuid":"281722510","full_name":"PeterH0323/Smart_Construction","owner":"PeterH0323","description":"Base on YOLOv5 Head Person Helmet Detection on Construction Sites，基于目标检测工地安全帽和禁入危险区域识别系统，🚀😆附 YOLOv5 训练自己的数据集超详细教程🚀😆2021.3新增可视化界面❗❗","archived":false,"fork":false,"pushed_at":"2024-04-11T21:56:54.000Z","size":110873,"stargazers_count":2401,"open_issues_count":12,"forks_count":475,"subscribers_count":25,"default_branch":"master","last_synced_at":"2025-05-15T10:04:43.250Z","etag":null,"topics":["detection","helmet","object-detection","python","pytorch","yolo","yolov5"],"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/PeterH0323.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-22T16:01:05.000Z","updated_at":"2025-05-15T01:33:30.000Z","dependencies_parsed_at":"2023-01-25T00:45:15.774Z","dependency_job_id":"a90bad9b-4136-42cb-a79f-17454e50aa00","html_url":"https://github.com/PeterH0323/Smart_Construction","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PeterH0323%2FSmart_Construction","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PeterH0323%2FSmart_Construction/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PeterH0323%2FSmart_Construction/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PeterH0323%2FSmart_Construction/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PeterH0323","download_url":"https://codeload.github.com/PeterH0323/Smart_Construction/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254319719,"owners_count":22051073,"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":["detection","helmet","object-detection","python","pytorch","yolo","yolov5"],"created_at":"2024-09-24T20:25:08.112Z","updated_at":"2025-05-15T10:05:42.007Z","avatar_url":"https://github.com/PeterH0323.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Smart_Construction\n\n[![](https://img.shields.io/github/stars/PeterH0323/Smart_Construction.svg)](https://github.com/PeterH0323/Smart_Construction/stargazers)\n\n**如果帮到您请给个 star :star2::star2::star2:，您的 star:star2: 是我最大的鼓励！**\n\n**如果您觉得我的项目不错，可以将我的 Github 链接随便转发；但如果您想发文章，请将我的 Github 链接放到文章开头的位置，谢谢！开源不易，请尊重每个人的汗水！**\n\n该项目是使用 `YOLOv5 v2.x` 的程序来训练在智能工地安全领域中头盔目标检测的应用\n\n## 可视化界面演示（2021.3 上新！）：\n:boom::boom::boom:新增可视化界面上线啦！！！！来一波演示！！！:boom::boom::boom:\n使用文档: [如何使用可视化工具](./doc/Visualize_Tool_Tutorial.md)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"tool_gif\" src=\"./doc/visualize_tool_gif_v2_1.gif\" width=\"55%\"\u003e\n\u003c/p\u003e\n\n## 纯图片再来一波演示！\n\n\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"output_1\" src=\"./doc/output_1.jpg\" width=\"45%\"\u003e\n  \u003cimg alt=\"output_2\" src=\"./doc/output_2.jpg\" width=\"45%\"\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"output_3\" src=\"./doc/output_3.jpg\" width=\"45%\"\u003e\n  \u003cimg alt=\"output_4\" src=\"./doc/output_4.jpg\" width=\"45%\"\u003e\n\u003c/p\u003e\n\n\n## 指标\n### yolov5s 为基础训练，`epoch = 50`\n|分类|P|R|mAP0.5|\n|---|---|---|---|\n|总体|0.884|0.899|0.888|\n|人体|0.846|0.893|0.877|\n|头|0.889|0.883|0.871|\n|安全帽|0.917|0.921|0.917|\n\n对应的**权重文件**：[百度云](https://pan.baidu.com/s/1ELPhtW-Q4G8UqEr4YrV_5A)，提取码: `b981`\n\n---\n\n### yolov5m 为基础训练，`epoch = 100`\n|分类|P|R|mAP0.5|\n|---|---|---|---|\n|总体|0.886|0.915|0.901|\n|人体|0.844|0.906|0.887|\n|头|0.9|0.911|0.9|\n|安全帽|0.913|0.929|0.916|\n\n对应的**权重文件**：[百度云](https://pan.baidu.com/s/10hlKrgpxVsw4d_vHnPHwEA)，提取码: `psst`\n\n---\n\n### yolov5l 为基础训练，`epoch = 100`\n|分类|P|R|mAP0.5|\n|---|---|---|---|\n|总体|0.892|0.919|0.906|\n|人体|0.856|0.914|0.897|\n|头|0.893|0.913|0.901|\n|安全帽|0.927|0.929|0.919|\n\n对应的**权重文件**：[百度云](https://pan.baidu.com/s/1iMZkRNXY1fowpQCcapFDqw)，提取码: `a66e`\n\n---\n\n# 1.YOLO v5训练自己数据集教程\n使用的数据集：[Safety-Helmet-Wearing-Dataset](https://github.com/njvisionpower/Safety-Helmet-Wearing-Dataset) ，感谢这位大神的开源数据集！\n\n\u003e 本文结合 [YOLOv5官方教程](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 来写\n\n## 环境准备\n首先确保自己的环境：\n\n```text\n    Python\u003e=3.7\n    Pytorch==1.5.x\n    PyQt5==5.15.3\n    PyQtChart==5.15.3\n    PyQt5-tools\n    GPUtil\n```\n\n或者使用我的环境（推荐）\n```shell script\npip install -r requirements.txt\n```\n\n## 官方权重\n我已上传到一份到百度云：[下载链接](https://pan.baidu.com/s/1mSIjDAzfiJd1fqSxIYzRDA) , 密码: `44qm`\n\n## 训练自己的数据\n\n#### 提示：\n**关于增加数据集分类的方法，请看【[5. 增加数据集的分类](#5-增加数据集的分类)】**\n\n---\n\n\n### 1.1 创建自己的数据集配置文件\n\n因为我这里只是判断 【人没有带安全帽】、【人有带安全帽】、【人体】 3个类别 ，基于 `data/coco128.yaml` 文件，创建自己的数据集配置文件 `custom_data.yaml`\n\n```yaml\n\n# 训练集和验证集的 labels 和 image 文件的位置\ntrain: ./score/images/train\nval: ./score/images/val\n\n# number of classes\nnc: 3\n\n# class names\nnames: ['person', 'head', 'helmet']\n```\n\n### 1.2 创建每个图片对应的标签文件\n\n你可以使用 `data/gen_data/gen_head_helmet.py` 来将` VOC` 的数据集转换成 `YOLOv5` 训练需要用到的格式。\n\n使用标注工具类似于 [Labelbox](https://labelbox.com/) 、[CVAT](https://github.com/opencv/cvat) 、[精灵标注助手](http://www.jinglingbiaozhu.com/) 标注之后，需要生成每个图片对应的 `.txt` 文件，其规范如下：\n- 每一行都是一个目标\n- 类别序号是零索引开始的（从0开始）\n- 每一行的坐标 `class x_center y_center width height` 格式\n- 框坐标必须采用**归一化的 xywh**格式（从0到1）。如果您的框以像素为单位，则将`x_center`和`width`除以图像宽度，将`y_center`和`height`除以图像高度。代码如下：\n\n```python\nimport numpy as np\ndef convert(size, box):\n    \"\"\"\n    将标注的 xml 文件生成的【左上角x,左上角y,右下角x，右下角y】标注转换为yolov5训练的坐标\n    :param size: 图片的尺寸： [w,h]\n    :param box: anchor box 的坐标 [左上角x,左上角y,右下角x,右下角y,]\n    :return: 转换后的 [x,y,w,h]\n    \"\"\"\n\n    x1 = int(box[0])\n    y1 = int(box[1])\n    x2 = int(box[2])\n    y2 = int(box[3])\n\n    dw = np.float32(1. / int(size[0]))\n    dh = np.float32(1. / int(size[1]))\n\n    w = x2 - x1\n    h = y2 - y1\n    x = x1 + (w / 2)\n    y = y1 + (h / 2)\n\n    x = x * dw\n    w = w * dw\n    y = y * dh\n    h = h * dh\n    return [x, y, w, h]\n```\n\n生成的 `.txt` 文件放置的名字是图片的名字，放置在 label 文件夹中，例如：\n```text\n./score/images/train/00001.jpg  # image\n./score/labels/train/00001.txt  # label\n```\n\n生成的 `.txt` 例子：\n```text\n1 0.1830000086920336 0.1396396430209279 0.13400000636465847 0.15915916301310062\n1 0.5240000248886645 0.29129129834473133 0.0800000037997961 0.16816817224025726\n1 0.6060000287834555 0.29579580295830965 0.08400000398978591 0.1771771814674139\n1 0.6760000321082771 0.25375375989824533 0.10000000474974513 0.21321321837604046\n0 0.39300001866649836 0.2552552614361048 0.17800000845454633 0.2822822891175747\n0 0.7200000341981649 0.5570570705458522 0.25200001196935773 0.4294294398277998\n0 0.7720000366680324 0.2567567629739642 0.1520000072196126 0.23123123683035374\n```\n\n### 1.3 文件放置规范\n文件树如下\n\n![](./doc/File_tree.png)\n\n### 1.4 选择一个您需要的模型\n在文件夹 `./models` 下选择一个你需要的模型然后复制一份出来，将文件开头的 `nc = ` 修改为数据集的分类数，下面是借鉴 `./models/yolov5s.yaml`来修改的\n\n```yaml\n# parameters\nnc: 3  # number of classes     \u003c============ 修改这里为数据集的分类数\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\n\n# anchors\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Focus, [64, 3]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, BottleneckCSP, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 9, BottleneckCSP, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, BottleneckCSP, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 1, SPP, [1024, [5, 9, 13]]],\n   [-1, 3, BottleneckCSP, [1024, False]],  # 9\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, BottleneckCSP, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, BottleneckCSP, [256, False]],  # 17\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, BottleneckCSP, [512, False]],  # 20\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, BottleneckCSP, [1024, False]],  # 23\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n\n```\n\n### 1.5 开始训练\n这里选择了 `yolov5s` 模型进行训练，权重也是基于 `yolov5s.pt` 来训练\n\n```shell script\npython train.py --img 640 \\\n                --batch 16 --epochs 10 --data ./data/custom_data.yaml \\\n                --cfg ./models/custom_yolov5.yaml --weights ./weights/yolov5s.pt\n```\n\n其中，`yolov5s.pt` 需要自行下载放在本工程的根目录即可，下载地址 [官方权重](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)\n\n### 1.6 看训练之后的结果\n训练之后，权重会保存在 `./runs` 文件夹里面的每个 `exp` 文件里面的 `weights/best.py` ，里面还可以看到训练的效果\n![](./doc/test_batch0_gt.jpg)\n\n# 2. 侦测\n侦测图片会保存在 `./inferenct/output/` 文件夹下\n\n运行命令：\n```shell script\npython detect.py --source   0  # webcam\n                            file.jpg  # image \n                            file.mp4  # video\n                            path/  # directory\n                            path/*.jpg  # glob\n                            rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa  # rtsp stream\n                            http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8  # http stream\n```\n\n例如使用我的 `s` 权重检测图片，可以运行以下命令，侦测图片会保存在 `./inferenct/output/` 文件夹下\n\n```bash\npython detect.py --source 图片路径 --weights ./weights/helmet_head_person_s.pt\n```\n\n# 3. 检测危险区域内是否有人\n\n## 3.1 危险区域标注方式\n我这里使用的是 [精灵标注助手](http://www.jinglingbiaozhu.com/) 标注，生成了对应图片的 json 文件\n\n## 3.2 执行侦测\n\n侦测图片会保存在 `./inferenct/output/` 文件夹下\n\n运行命令：\n```shell script\npython area_detect.py --source ./area_dangerous --weights ./weights/helmet_head_person_s.pt\n```\n\n## 3.3 效果：\n\n**危险区域会使用 *红色框* 标出来，同时，危险区域里面的人体也会被框出来，危险区域外的人体不会被框选出来**\n\n\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"area_output_1\" src=\"./doc/area_output_1.jpg\" width=\"45%\"\u003e\n  \u003cimg alt=\"area_output_2\" src=\"./doc/area_output_2.jpg\" width=\"45%\"\u003e\n\u003c/p\u003e\n\n\n# 4. 生成 ONNX\n## 4.1 安装 `onnx` 库\n\n```shell script\npip install onnx\n```\n\n## 4.2 执行生成\n\n```shell script\npython ./models/export.py --weights ./weights/helmet_head_person_s.pt --img 640 --batch 1\n```\n\n`onnx` 和 `torchscript` 文件会生成在 `./weights` 文件夹中\n\n# 5. 增加数据集的分类\n关于增加数据集分类的方法：\n\n`SHWD` 数据集里面的 `person` 指的是`头（head）`，没有 `人体` 的类别，先将现有的自己的数据集执行脚本生成 yolov5 需要的标签文件 `.txt`，之后再用 `yolov5x.pt` 加上 `yolov5x.yaml` ，使用指令检测出人体\n\n```shell script\npython detect.py --save-txt --source 自己数据集的文件目录 --weights ./weights/yolov5x.pt\n```\n\n`yolov5` 会推理出所有的分类，并在 `inference/output` 中生成对应图片的 `.txt` 标签文件；\n\n修改 `./data/gen_data/merge_data.py` 中的自己数据集标签所在的路径，执行这个python脚本，会进行 `人体(person)` 类型的合并 \n\n---\n\n**如果帮到您请给个 star ✨✨✨，您的 star 是我最大的鼓励！**\n\n**如果能帮到您的项目快速落地，可以请我喝杯奶茶☕**\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"./doc/BuyMeACoffee.jpg\" width=\"500\"/\u003e\n\u003c/div\u003e\n\n也可以加我的 WeChat 和我一起探讨更多的可能！**加我微信条件请看下面3条，加好友消息请备注：`Github Smart_Construction`。**\n\n❗ ❗ ❗**注意**❗ ❗ ❗\n\n**1、欢迎论文or项目合作**\n\n**2、毕业设计/课程设计 远程帮助需要收费（起步价 666）**\n\n**3、毕业设计、竞赛等咨询环境怎么配置，或者询问怎么操作的大佬们请先看文档，遇到问题请先百度或者学习相关基础，实在不懂了的话，请询问周边大佬，相关操作本人在README写得很清楚了，不想再回答相关问题**\n\n\u003cdiv align=center\u003e\n\u003cimg src=\"./doc/WeChat.jpg\" width=\"300\"/\u003e\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterh0323%2Fsmart_construction","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpeterh0323%2Fsmart_construction","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterh0323%2Fsmart_construction/lists"}