基于深度学习神经网络YOLOv5目标检测的安全帽识别系统

第一步:YOLOv5介绍

YOLOv5是一种目标检测算法,它是YOLO(You Only Look Once)系列的最新版本。YOLOv5在YOLOv4的基础上进行了改进和优化,以提高检测的准确性和速度。

YOLOv5采用了一些新的技术和方法来改进目标检测的性能。其中包括以下几个方面:

  1. 损失函数:YOLOv5使用了CIOU_Loss作为bounding box的损失函数。CIOU_Loss是一种改进的IOU_Loss,可以更好地衡量目标框的位置和大小。

  2. 非极大值抑制(NMS):YOLOv5使用NMS来抑制重叠的边界框,以减少重复检测的问题。

  3. 聚类anchors:YOLOv5使用k-means聚类算法来生成anchors,这些anchors用于检测不同尺度的目标。

总的来说,YOLOv5在YOLOv4的基础上进行了一些改进和优化,以提高目标检测的准确性和速度。

标注数据,YOLOv5的训练和测试步骤,各路大神都已经做了很多工作,我就不再写了,这里有几个写的比较好的博客可以参考:

无脑008——yolov5目标检测全流程,训练自己的庞大数据集,半自动标注数据集_python 实现yolov5s 目标检测训练-CSDN博客


基于YOLOV5的数据集标注&训练,Windows/Linux/Jetson Nano多平台部署全流程-CSDN博客

使用 YOLOv5 训练自建数据集教程 - 知乎

第二步:YOLOv5网络结构

第三步:代码展示

"""Run inference with a YOLOv5 model on images, videos, directories, streams Usage: $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640 """ import argparse import sys import time from pathlib import Path import cv2 import torch import torch.backends.cudnn as cudnn FILE = Path(__file__).absolute() sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path from models.experimental import attempt_load from utils.datasets import LoadStreams, LoadImages from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box from utils.plots import colors, plot_one_box from utils.torch_utils import select_device, load_classifier, time_sync @torch.no_grad() def run(weights='helmet.pt', # model.pt path(s) source='data/images', # file/dir/URL/glob, 0 for webcam imgsz=640, # inference size (pixels) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project='runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference ): save_img = not nosave and not source.endswith('.txt') # save inference images webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( ('rtsp://', 'rtmp://', 'http://', 'https://')) # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Initialize set_logging() device = select_device(device) half &= device.type != 'cpu' # half precision only supported on CUDA # Load model w = weights[0] if isinstance(weights, list) else weights classify, pt, onnx = False, w.endswith('.pt'), w.endswith('.onnx') # inference type stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults if pt: model = attempt_load(weights, map_location=device) # load FP32 model stride = int(model.stride.max()) # model stride names = model.module.names if hasattr(model, 'module') else model.names # get class names names[0] = "nohat" if half: model.half() # to FP16 if classify: # second-stage classifier modelc = load_classifier(name='resnet50', n=2) # initialize modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval() elif onnx: check_requirements(('onnx', 'onnxruntime')) import onnxruntime session = onnxruntime.InferenceSession(w, None) imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader if webcam: view_img = check_imshow() cudnn.benchmark = True # set True to speed up constant image size inference dataset = LoadStreams(source, img_size=imgsz, stride=stride) bs = len(dataset) # batch_size else: dataset = LoadImages(source, img_size=imgsz, stride=stride) bs = 1 # batch_size vid_path, vid_writer = [None] * bs, [None] * bs # Run inference if pt and device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once t0 = time.time() for path, img, im0s, vid_cap in dataset: if pt: img = torch.from_numpy(img).to(device) img = img.half() if half else img.float() # uint8 to fp16/32 elif onnx: img = img.astype('float32') img /= 255.0 # 0 - 255 to 0.0 - 1.0 if len(img.shape) == 3: img = img[None] # expand for batch dim # Inference t1 = time_sync() if pt: visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False pred = model(img, augment=augment, visualize=visualize)[0] elif onnx: pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img})) # NMS pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) t2 = time_sync() # Second-stage classifier (optional) if classify: pred = apply_classifier(pred, modelc, img, im0s) # Process predictions for i, det in enumerate(pred): # detections per image if webcam: # batch_size >= 1 p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count else: p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) p = Path(p) # to Path save_path = str(save_dir / p.name) # img.jpg txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt s += '%gx%g ' % img.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh imc = im0.copy() if save_crop else im0 # for save_crop if len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, -1].unique(): n = (det[:, -1] == c).sum() # detections per class s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string # Write results for *xyxy, conf, cls in reversed(det): if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format with open(txt_path + '.txt', 'a') as f: f.write(('%g ' * len(line)).rstrip() % line + '\n') if save_img or save_crop or view_img: # Add bbox to image c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness) if save_crop: save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) # Print time (inference + NMS) print(f'{s}Done. ({t2 - t1:.3f}s)') # Stream results if view_img: cv2.imshow(str(p), im0) cv2.waitKey(1) # 1 millisecond # Save results (image with detections) if save_img: if dataset.mode == 'image': cv2.imwrite(save_path, im0) else: # 'video' or 'stream' if vid_path[i] != save_path: # new video vid_path[i] = save_path if isinstance(vid_writer[i], cv2.VideoWriter): vid_writer[i].release() # release previous video writer if vid_cap: # video fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) else: # stream fps, w, h = 30, im0.shape[1], im0.shape[0] save_path += '.mp4' vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) vid_writer[i].write(im0) if save_txt or save_img: s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' print(f"Results saved to {colorstr('bold', save_dir)}{s}") if update: strip_optimizer(weights) # update model (to fix SourceChangeWarning) print(f'Done. ({time.time() - t0:.3f}s)') return im0 def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--weights', nargs='+', type=str, default='helmet.pt', help='model.pt path(s)') parser.add_argument('--source', type=str, default='0', help='file/dir/URL/glob, 0 for webcam') parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--view-img', action='store_true', help='show results') parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') parser.add_argument('--nosave', action='store_true', help='do not save images/videos') parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') parser.add_argument('--augment', action='store_true', help='augmented inference') parser.add_argument('--visualize', action='store_true', help='visualize features') parser.add_argument('--update', action='store_true', help='update all models') parser.add_argument('--project', default='runs/detect', help='save results to project/name') parser.add_argument('--name', default='exp', help='save results to project/name') parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') opt = parser.parse_args() return opt def main(opt): print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) check_requirements(exclude=('tensorboard', 'thop')) run(**vars(opt)) if __name__ == "__main__": opt = parse_opt() main(opt)

第四步:运行

图片识别效果:

第五步:整个工程的内容

项目完整文件下载请见演示与介绍视频的简介处给出:➷➷➷

https://www.bilibili.com/video/BV13qUxYsEB7/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1150403.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

dy bd-ticket-guard-client-data 逆向分析

声明 本文章中所有内容仅供学习交流使用,不用于其他任何目的,抓包内容、敏感网址、数据接口等均已做脱敏处理,严禁用于商业用途和非法用途,否则由 此产生的一切后果均与作者无关! 部分python代码 cp execjs.compil…

计算机毕设 java 基于 Java 的心理咨询系统的设计与实现 线上心理咨询服务平台 心理疏导预约管理系统

计算机毕设 java 基于 Java 的心理咨询系统 sb3kn9(配套有源码 程序 mysql 数据库 论文)本套源码可以先看具体功能演示视频领取,文末有联 xi 可分享随着心理健康意识的提升,人们对心理咨询的需求逐渐增加,传统线下咨询…

2026必备!9个一键生成论文工具,助本科生轻松搞定毕业论文!

2026必备!9个一键生成论文工具,助本科生轻松搞定毕业论文! AI 工具如何改变论文写作的未来 随着人工智能技术的飞速发展,越来越多的本科生开始借助 AI 工具来提升论文写作效率。尤其是在当前 AIGC(人工智能生成内容&am…

5分钟搞定!Win11Debloat让你的Windows系统飞起来 [特殊字符]

5分钟搞定!Win11Debloat让你的Windows系统飞起来 🚀 【免费下载链接】Win11Debloat 一个简单的PowerShell脚本,用于从Windows中移除预装的无用软件,禁用遥测,从Windows搜索中移除Bing,以及执行各种其他更改…

IF=33.2多比较组差异分析火山图

适用场景 生物信息学/组学研究(转录组、蛋白组等)中专用的差异表达结果可视化: 研究对象包含N个分组(如多组织、多细胞亚群、多处理组),需展示各分组差异分子的整体分布与分组细节; 需筛选 的显著性差异分子,通过火山图呈现差异幅度与统计显著性; 学术论文 / 汇报配…

【计算机毕业设计案例】基于python-CNN卷积神经网络的鱼类识别

博主介绍:✌️码农一枚 ,专注于大学生项目实战开发、讲解和毕业🚢文撰写修改等。全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围:&am…

Vue.js 深度开发指南:从数据绑定到状态管理的最佳实践

一、数据绑定的2026最佳实践1. 性能优化新特性编译时优化&#xff1a;Vue 3.4新增的v-memo指令可缓存模板子树&#xff0c;适合静态内容区块vue<div v-memo"[user.name]"> <!-- 只有user.name变化时才会重新渲染 --> <Profile :user"user" …

深度学习毕设选题推荐:基于python-CNN卷积神经网络的宠物行为训练识别

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

网络安全认证全景攻略:CISSP、CEH、OSCP深度备考策略与职业发展路径

网络安全认证全景攻略&#xff1a;CISSP、CEH、OSCP深度备考策略与职业发展路径引言&#xff1a;网络安全认证的价值与战略选择在数字化转型加速的时代&#xff0c;网络安全已成为企业和组织的核心战略需求。根据(ISC) 2023年网络安全劳动力研究报告&#xff0c;全球网络安全人…

计算机毕设 java 基于 Java 的心理健康测试系统的设计与实现 校园心理健康服务平台 心理状态评估管理系统

计算机毕设 java 基于 Java 的心理健康测试系统 k724o9&#xff08;配套有源码 程序 mysql 数据库 论文&#xff09;本套源码可以先看具体功能演示视频领取&#xff0c;文末有联 xi 可分享随着社会压力的增大&#xff0c;校园师生对心理健康服务的需求日益增长&#xff0c;传统…

Scarab模组管理器:革命性的一站式空洞骑士模组管理解决方案

Scarab模组管理器&#xff1a;革命性的一站式空洞骑士模组管理解决方案 【免费下载链接】Scarab An installer for Hollow Knight mods written in Avalonia. 项目地址: https://gitcode.com/gh_mirrors/sc/Scarab 还在为《空洞骑士》模组安装的繁琐流程而头疼吗&#x…

基于深度学习神经网络MTCNN的人脸检测系统源码

一. mtcnn概述 MTCNN&#xff0c;英文全称是Multi-task convolutional neural network&#xff0c;中文全称是多任务卷积神经网络&#xff0c;该神经网络将人脸区域检测与人脸关键点检测放在了一起。 二. mtcnn的网络结构 mtcnn从整体上划分分为P-Net、R-Net、和O-Net三层网络结…

【计算机毕设选题推荐】基于Django+Spark健康风险预测数据可视化分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习 数据挖掘

✍✍计算机编程指导师 ⭐⭐个人介绍&#xff1a;自己非常喜欢研究技术问题&#xff01;专业做Java、Python、小程序、安卓、大数据、爬虫、Golang、大屏等实战项目。 ⛽⛽实战项目&#xff1a;有源码或者技术上的问题欢迎在评论区一起讨论交流&#xff01; ⚡⚡如果你遇到具体的…

【计算机毕业设计案例】基于python-深度学习的混凝土马路和泥地马路识别

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

深度学习毕设项目推荐-基于python-CNN卷积神经网络的鱼类识别

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

计算机深度学习毕设实战-基于python-CNN卷积神经网络的宠物行为训练识别

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

大数据领域Hive在零售行业的数据处理应用

Hive在零售行业的数据处理应用&#xff1a;从痛点到解决方案的全流程实践 引言&#xff1a;零售行业的“数据焦虑”与Hive的救赎 1. 零售人的痛点&#xff1a;当数据量超过“Excel极限” 作为零售行业的数据分析师&#xff0c;你是否遇到过这样的场景&#xff1f; 月底统计全国…

DeepSeek V4模型即将来袭,编程能力或将超越GPT与Claude

DeepSeek计划于2月中旬推出主打编程能力的新一代AI模型V4&#xff0c;据内部测试&#xff0c;其在代码相关任务上的表现可能优于Claude和GPT系列。V4在处理超长代码提示方面有新突破&#xff0c;对复杂软件开发者大有帮助。恰逢中国春节发布&#xff0c;网友调侃DeepSeek"…

深度学习毕设项目推荐-基于python-深度学习的混凝土马路和泥地马路识别

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

论文AIGC率太高怎么办?10个让我论文AI率从82.5%降到5%的工具,亲测有效

凌晨两点&#xff0c;我盯着屏幕上刺眼的“AI风险&#xff1a;82.7%”&#xff0c;感觉整个胃都在抽搐。 那是我用了一周时间&#xff0c;读了三十多篇文献&#xff0c;反复推翻三次才写成的第三章啊。导师的批注像刀一样&#xff1a;“论述流畅但缺乏‘人味儿’&#xff0c;请…