Python+Yolov5反光衣黄色马甲特征识别监测快速锁定目标人物体

news2024/9/24 20:21:52

 程序示例精选

Python+Yolov5反光衣识别

如需安装运行环境或远程调试,见文章底部微信名片,由专业技术人员远程协助!

前言

Yolov5比较Yolov4,Yolov3等其他识别框架,速度快,代码结构简单,识别效率高,对硬件要求比较低。这篇博客针对<<Python Yolov5火焰烟雾识别>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


文章目录

        一、所需工具软件

        二、使用步骤

                1. 引入库

                2. 识别图像特征

                3. 识别参数定义

                4. 运行结果

         三在线协助


一、所需工具软件

          1. Python3.6以上

          2. Pycharm代码编辑器

          3. Torch, OpenCV库

二、使用步骤

1.引入库

代码如下(示例):

import cv2
import torch
from numpy import random
 
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
    scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized

2.识别图像特征

代码如下(示例):

def detect(save_img=False):
    source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://'))
 
    # Directories
    save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.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(opt.device)
    half = device.type != 'cpu'  # half precision only supported on CUDA
 
    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    stride = int(model.stride.max())  # model stride
    imgsz = check_img_size(imgsz, s=stride)  # check img_size
    if half:
        model.half()  # to FP16
 
    # Second-stage classifier
    classify = False
    if classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
 
    # Set Dataloader
    vid_path, vid_writer = None, None
    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)
    else:
        save_img = True
        dataset = LoadImages(source, img_size=imgsz, stride=stride)
 
    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
 
    # Run inference
    if 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:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)
 
        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]
 
        # Apply NMS
        pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
        t2 = time_synchronized()
 
        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)
 
        # Process detections
        for i, det in enumerate(pred):  # detections per image
            if webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
            else:
                p, s, im0, frame = path, '', im0s, 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
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
 
 
                # 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 opt.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 view_img:  # Add bbox to image
                        label = f'{names[int(cls)]} {conf:.2f}'
                        plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
 
            # Print time (inference + NMS)
            print(f'{s}Done. ({t2 - t1:.3f}s)')
 
 
            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video'
                    if vid_path != save_path:  # new video
                        vid_path = save_path
                        if isinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release()  # release previous video writer
 
                        fourcc = 'mp4v'  # output video codec
                        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))
                        vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
                    vid_writer.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 {save_dir}{s}")
 
    print(f'Done. ({time.time() - t0:.3f}s)')
    
    print(opt)
    check_requirements()
 
    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

该处使用的url网络请求的数据。

3.识别参数定义:

代码如下(示例):

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='yolov5_best_road_crack_recog.pt', help='model.pt path(s)')
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
    parser.add_argument('--view-img', action='store_true', help='display results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--classes', nargs='+', type=int, default='0', 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('--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')
    opt = parser.parse_args()
    
    print(opt)
    check_requirements()
 
    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

4.运行结果如下: 

 

 

三、在线协助: 

如需安装运行环境或远程调试,见文章底部微信名片,由专业技术人员远程协助!

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

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

相关文章

计算机网络进阶 ---- MGRE ---- NHRP ---- 详解

一、MGRE&#xff08;多点GRE&#xff09;&#xff1a; 属于 NBMA 网络类型&#xff1b;在所有要连通的网络之间仅需要构建一个MA网段即可&#xff1b;且仅可以存在一个 固定的 IP地址&#xff0c;看作中心站点&#xff1b;其他分支站点可以是动态的 IP地址&#xff0c;节省成…

从recat源码角度看setState流程

setState setState() 将对组件 state 的更改排入队列批量推迟更新&#xff0c;并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件。其实setState实际上不是异步&#xff0c;只是代码执行顺序不同&#xff0c;有了异步的感觉。 使用方法 setState(stateChange | u…

助力生产质量检验,基于YOLOV5实现香烟质量缺陷检测

生产质量环境的检验始终是一个热门的应用场景&#xff0c;在之前一些项目和文章中我也做过一些相关的事情&#xff0c;比如PCB电路板相关的&#xff0c;如下&#xff1a;《助力质量生产&#xff0c;基于目标检测模型MobileNetV2-YOLOv3-Lite实现PCB电路板缺陷检测》本质的目的就…

含泪赔了近200万,我终于明白不是什么人都能干电商的……

文|螳螂观察 作者|图霖 又是一年年货节&#xff0c;围绕电商相关话题的讨论正在增多。 都说现在入行做电商十有九亏&#xff0c;但《螳螂观察》注意到一组数据&#xff1a;截至7月31日&#xff0c;过去一年入淘创业者的数量仍在增长&#xff0c;淘宝天猫净增了近120万商家&a…

每天五分钟机器学习:如何使用误差分析来构造最优的异常检测算法

本文重点 在异常检测算法中,我们要做的事情之一就是使用正态(高斯)分布来对特征向量进行建模p(xi;μi,σi),所以输入到算法中的特征变量很重要。 特征变量不符合高斯分布怎么办 首先我们需要知道一点,有些特征变量的数据并不符合高斯分布,但是我们假设它们符合高斯分…

中西方哲学史概要

中西方哲学史概要 哲学的定义 哲学在古希腊是 “爱智慧” 的意思&#xff0c;一切的知识都可以称之为“哲学”&#xff0c;它是对基本和普遍之问题研究的学科&#xff0c;是关于世界观的理论体系。很多人说懂哲学的人很可怕&#xff0c;其实这是错误的&#xff0c;因为真正懂哲…

【linux命令】查看进程活动的命令

ps进程信息 ps用于显示系统内的所有进程 -l或l 采用详细的格式来显示进程状况 常用方式&#xff1a; ps -elf 和ps -ef rootecs-x-large-2-linux-20200309113627:/home/etcd_msg_server# ps -ef UID PID PPID C STIME TTY TIME CMD root 1 …

C++入门 -- 模板初阶与string简介

目录 模板&#xff1a; 函数模板 类模板 STL简介&#xff1a; string: string类对象的常见构造 string类对象的容量操作 string类对象的访问及遍历 模板&#xff1a; 在C语言阶段&#xff0c;当我们需要交换两个int类型的数据就需要写一个支持int类型交换的Swap函数…

如何使用ArcGIS Pro自动矢量化建筑

概述相信你在使用ArcGIS Pro的时候已经发现了一个问题&#xff0c;那就是ArcGIS Pro没有ArcScan&#xff0c;确实在ArcGIS Pro中Esri移除了ArcScan&#xff0c;没有了ArcScan我们如何自动矢量化地图&#xff0c;从地图中提取建筑等要素呢&#xff0c;这里为大家介绍另外一种方法…

可视化深度学习模型的方法/工具

介绍 可以使用 TensorBoard 来可视化深度学习模型。TensorBoard 是 TensorFlow 中的一个可视化工具,可以帮助您在训练期间和训练后可视化模型的训练曲线、模型结构、激活值和权值分布等信息。可以使用 TensorBoard 的命令行工具或在 Jupyter 笔记本中使用 TensorBoard magic …

【Linux】权限理解(粘滞位设置)

目  录1 权限的概念2 权限管理2.1 文件类型及其访问权限2.2 文件权限值的表示方法2.3 文件访问权限设置2.4 目录权限&#xff08;粘滞位&#xff09;1 权限的概念 所谓权限&#xff0c;实际上是对人的约束&#xff0c;在Linux中&#xff0c;是对普通用户的约束。一件事情&…

蓝桥杯嵌入式之 Keil 仿真与调试

这篇文章为大家讲解 蓝桥杯嵌入式的 Keil 仿真与调试 &#xff0c; 这在比赛和今后的工作中都是常用的。大家看完后一定会对此有一个深刻的认识。 文章目录前言一、调试器的准备工作&#xff1a;1.在 Keil uVision集成开发环境下&#xff0c;选择CMSIS-DAP Debugger调试器。2.在…

final关键字深入解析

final关键字特性 final关键字在java中使用非常广泛&#xff0c;可以申明成员变量、方法、类、本地变量。一旦将引用声明为final&#xff0c;将无法再改变这个引用。final关键字还能保证内存同步&#xff0c;本博客将会从final关键字的特性到从java内存层面保证同步讲解。这个内…

SpringBoot项目从18.18M瘦身到0.18M

一、前言 SpringBoot部署起来虽然简单&#xff0c;如果服务器部署在公司内网&#xff0c;速度还行&#xff0c;但是如果部署在公网&#xff08;阿里云等云服务器上&#xff09;&#xff0c;部署起来实在头疼&#xff1a;编译出来的 Jar 包很大&#xff0c;如果工程引入了许多开…

GAMES101作业6及课程总结(重点解决SAH扩展作业)

这次作业相对于作业5会麻烦一点点&#xff0c;而且框架相较于作业五的也麻烦了一点&#xff0c;当然作业的难点其实主要还是在扩展作业SAH那块。 目录课程总结与理解&#xff08;光线追踪&#xff09;框架梳理作业一&#xff1a;光线生成作业二&#xff1a;光线-三角形相交作业…

Neo4j图数据库 批量写入与查询

1 前言 1-1 简介 工作中需要对所有的实体数据进行存储构建实体知识图谱&#xff0c;为基于知识图谱的问答提供数据基础。选择使用Neo4j作为数据库进行存储。以下是关于Neo4j的简介。 1-2 任务背景 将处理好的实体数据(共计1100万)写入图数据库中&#xff0c;并且提供查询接口…

量子计算(二十):量子算法简介

文章目录 量子算法简介 一、概述 二、量子经典混合算法 量子算法简介 一、概述 量子算法是在现实的量子计算模型上运行的算法&#xff0c;最常用的模型是计算的量子电路模型。经典&#xff08;或非量子&#xff09;算法是一种有限的指令序列&#xff0c;或一步地解决问题的…

乐视--996、内卷、裁员环境下一朵“奇葩”

在2022.12.28日我们发表了一篇“为什么四天工作制才是企业良药&#xff0c;而非裁员”,大家认为四天工作制与我们的距离就像实现“一个小目标”一样&#xff0c;不太可能。这不他来了&#xff0c;乐视来了&#xff0c;他真的来了&#xff0c;“鸡毛真的上天了”。他来了他来了他…

SQL技巧:使用AVG()函数计算占比

计算方式对比 一般计算占比&#xff0c;比如转换率、留存率等&#xff0c;都是先分组求和再相除得到结果&#xff0c;但是在一定的条件下&#xff0c;可以直接使用AVG()求出百分比。 比如&#xff0c;要求统计报名转化率&#xff0c;报名转化率公式为转化率报名人数/浏览人数…

内核解读之内存管理(8)内存模型

文章目录基本的术语CONFIG_FLATMEM&#xff08;平坦内存模型&#xff09;稀疏的内存模型基本的术语 在介绍内存模型之前需要了解一些基本的知识。 1、什么是page frame&#xff1f; 在linux操作系统中&#xff0c;物理内存被分成一页页的page frame来管理&#xff0c;具体pa…