Python+Yolov5跌倒检测 摔倒检测 人物目标行为 人体特征识别

news2024/9/28 5:32:56

Python+Yolov5跌倒检测 摔倒检测 人物目标行为 人体特征识别

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

前言

这篇博客针对<<Python+Yolov5跌倒摔倒人体特征识别>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。

文章目录

一、所需工具软件

二、使用步骤

1. 引入库

2. 识别图像特征

3. 参数设置

4. 运行结果

三、在线协助

一、所需工具软件

1. Pycharm, Python

2. Qt, 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.识别图像特征

代码如下(示例):

defdetect(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_sizeif half:
        model.half()  # to FP16# Second-stage classifier
    classify = Falseif 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, Noneif 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 ifhasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ inrange(3)] for _ in names]
 
    # Run inferenceif 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.0if 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 Classifierif classify:
            pred = apply_classifier(pred, modelc, img, im0s)
 
        # Process detectionsfor i, det inenumerate(pred):  # detections per imageif 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'elsef'_{frame}')  # img.txt
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwhiflen(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
 
 
                # Write resultsfor *xyxy, conf, cls inreversed(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 formatwithopen(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
                        ifisinstance(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()

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()
  1. 运行结果如下

三、在线协助:

如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!
1)远程安装运行环境,代码调试
2)Qt, C++, Python入门指导
3)界面美化
4)软件制作

博主推荐文章:https://blog.csdn.net/alicema1111/article/details/123851014

个人博客主页:https://blog.csdn.net/alicema1111?type=blog

博主所有文章点这里:https://blog.csdn.net/alicema1111?type=blog

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

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

相关文章

Torch中常见插值方式及各自的优缺点

Pytorch常见插值方式及优缺点1 插值算法2 Pytorch中能看到的插值方式3 Nearest插值法3.1 方法介绍3.2 优缺点4 Linear插值法4.1 方法接受4.2 优缺点5 Bilinear插值法5.1 方法介绍5.2 优缺点6 Bicubic插值法6.1 方法介绍6.2 优缺点7 Trlinear插值法7.1 方法介绍7.2 优缺点8 图片…

C#窗体应用程序可能会遇到的一些奇怪问题

最近在上程序实训课&#xff0c;写一个管理程序&#xff0c;主要是用了C#&#xff0c;在VS2017平台&#xff0c;在开发过程中自然是少不了很多奇怪的问题&#xff0c;做个记录。 有下面几个问题: 问题1&#xff1a;.Conversion failed when converting from a character stri…

小红书“复刻”微信,微信“内造”小红书

配图来自Canva可画 随着互联网增长红利逐渐见顶&#xff0c;各大互联网平台对流量的争夺变得愈发激烈。而为了寻找新的业务可能性&#xff0c;各家都在不遗余力地拓宽自身边界。在此背景下&#xff0c;目前最为“吸睛”和“吸金”的社交、电商、种草、短视频等领域&#xff0c…

linux创建文件软连接和硬链接详解

前言linux系统中链接文件仔细区分可以分为软连接&#xff08;符号链接&#xff09;和硬链接。软链接比硬链接应用更广泛&#xff0c;所以也可以认为linux链接文件就是指软链接文件。本文将会在第2部分介绍创建软链接和硬链接的基本命令&#xff0c;在第3部分从linux文件系统的角…

Gated Activations门控激活单元

门控激活 在架构图的方框部分&#xff0c;您会注意到扩张卷积输出分成两个分支&#xff0c;随后通过逐元素乘法重新组合。这描绘了一个门控激活单元&#xff0c;其中我们将tanh激活分支解释为一个学习过滤器&#xff0c;将sigmoid激活分支解释为一个学习门&#xff0c;用于调节…

(五十五)大白话更新数据的时候,自动维护的聚簇索引到底是什么?

上一次我们给大家讲了一下基于主键如何组织一个索引&#xff0c;然后建立索引之后&#xff0c;如何基于主键在索引中快速定位到那行数据所在的数据页&#xff0c;再如何进入数据页快速到定位那行数据&#xff0c;大家看下面的图。 我们今天就先基于上面的图&#xff0c;把按照主…

·神经网络

目录11神经网络demo112神经网络demo213神经网络demo320tensorflow2.0 安装教程,所有安装工具&#xff08;神经网络&#xff09;21神经网络-线性回归- demo122神经网络-线性回归- demo228神经网络-多层感知- demo1目录11神经网络demo1 package com.example.xxx; import java.ut…

玩转qsort——“C”

各位CSDN的uu们你们好呀&#xff0c;今天小雅兰的内容还是我们的深度剖析指针呀&#xff0c;上篇博客我们学习了回调函数这个知识点&#xff0c;但是没有写完&#xff0c;因为&#xff1a;小雅兰觉得qsort值得单独写出来&#xff01;&#xff01;&#xff01;好啦&#xff0c;就…

Ae:合成设置

Ae菜单&#xff1a;合成/合成设置Composition Settings快捷键&#xff1a;Ctrl K合成名称Composition Name为合成定义一个恰当的名称以便于查找和识别。◆ ◆ ◆基本Basic有关合成的一些常规设置。预设Preset给出了适合各种平台的常用预设。也可以创建并保存自己的自定义预设…

项目请求地址自动加上了本地ip的解决方式

一般情况下来说都是一些粗心大意的问题导致的 场景一&#xff1a;少加了/ 场景二&#xff1a;前后多加了空格 场景三&#xff1a;拼接地址错误![

改进YOLO系列 | ICLR2022 | OMNI-DIMENSIONAL DYNAMIC CONVOLUTION: 全维动态卷积

单个静态卷积核是现代卷积神经网络(CNNs)的常见训练范式。然而,最近的动态卷积研究表明,学习加权为其输入依赖注意力的n个卷积核的线性组合可以显著提高轻量级CNNs的准确性,同时保持高效的推理。然而,我们观察到现有的作品通过卷积核空间的一个维度(关于卷积核数量)赋予…

SpringSecurity学习(二)自定义资源认证规则、自定义登录页面、自定义登录(成功/失败)处理、用户信息获取

文章目录一、自定义认证1. 自定义资源权限规则二、自定义登录页面1. 引入thymeleaf依赖&#xff0c;并配置2. 配置SecurityCfg的securityFilterChain实例3. 编写login.html注意&#xff1a;三、自定义登录成功处理1. 编写JsonAuthenticationSuccessHandler处理器&#xff0c;返…

如何在excel中创建斐波那契数列

斐波那契数列&#xff08;Fibonacci sequence&#xff09;&#xff0c;又称黄金分割数列&#xff0c;因数学家莱昂纳多斐波那契&#xff08;Leonardo Fibonacci&#xff09;以兔子繁殖为例子而引入&#xff0c;故又称为“兔子数列”&#xff0c;指的是这样一个数列&#xff1a;…

软件测试是个人就能做?恕我直言,你可能是个“纯粹”的测试工具人,BUG收集器

作为过来人的我和你说说软件测试的真正情况。 前言 一个软件做出来&#xff0c;最不能少的是谁&#xff1f;毫无疑问是开发&#xff0c;开发是最了解软件运作的那个人&#xff0c;早期就有不少一人撸网站或者APP的例子&#xff0c;相当于一个人同时是产品、研发、测试、运维等…

学习笔记-架构的演进之服务容错策略-服务发现-3月day01

文章目录前言服务容错容错策略附前言 “容错性设计”&#xff08;Design for Failure&#xff09;是微服务的一个核心原则。 使用微服务架构&#xff0c;拆分出的服务越来越多&#xff0c;也逐渐导致以下问题&#xff1a; 某一个服务的崩溃&#xff0c;会导致所有用到这个服务…

webrtc拥塞控制算法对比-GCC vs BBR vs PCC

1.前言现有集成在webrtc中的拥塞控制算法有三种, 分别是: 谷歌自研发的gcc, 谷歌自研发的BBR算法, 斯坦福大学提出的基于机器学习凸优化的PCC算法. 本文将探讨一下三个算法的区别和优缺点。2.背景迈聆会议从17年到现在, 一直使用的是基于谷歌的gcc算法自研的Omcc算法(optimizat…

【基于机器学习的推荐系统项目实战-1】初识推荐系统

本文目录一、为什么我们需要推荐系统&#xff1f;二、推荐系统的发展阶段三、推荐系统模型四、通用推荐系统框架4.1 数据生产4.2 数据存储4.3 算法召回4.4 结果排序4.5 结果应用4.6 新浪微博的框架开源结构图五、推荐常用特征5.1 用户特征5.2 物品特征六、推荐常用算法七、结果…

正点原子IMX6ULL开发板-liunx内核移植例程-uboot卡在Starting kernel...问题

环境 虚拟机与Linux版本&#xff1a; VMware 17.0.0 Ubuntu16 NXP提供的U-boot与Linux版本&#xff1a; u-boot:uboot-imx-rel_imx_4.1.15_2.1.0_ga.tar.bz2 linux:linux-imx-rel_imx_4.1.15_2.1.0_ga.tar.bz2 开发板&#xff1a; 正点原子-IMX6ULL_EMMC版本&#xff0c;底板版…

国产光刻机再突破后,能实现7nm芯片量产?专家:别再盲目自大

众所周知&#xff0c;不能生产高端芯片&#xff0c;一直都是我国芯片产业一个无法抹去的痛。加上老美近几年的刻意打压&#xff0c;部分中芯企更是苦不堪言&#xff0c;因此大部分人心里也都憋着一口气&#xff0c;这几年也是铆足了劲&#xff0c;大力推动国产芯片技术的发展。…

小家电品牌私域增长解决方案来了

小家电品牌的私域优势 01、行业线上化发展程度高 相对于大家电动辄上千上万元的价格&#xff0c;小家电的客单价较低。而且与大家电偏刚需属性不同的是&#xff0c;小家电的消费需求侧重场景化&#xff0c;用户希望通过购买小家电来提高自身的生活品质。这就决定了用户的决策…