基于yolov8和openpose人体骨骼关键点实现的摔倒姿态识别检测系统实现

【参考源码】

GitHub - HRonaldo/Openpose_YOLO

本项目参考上面框架进行全面改进,改进如下:

(1)将检测框架换成当前最流行框架yolov8,并封装成类实现模块化设计。关于yolov5优化项目可以访问:https://blog.csdn.net/FL1623863129/article/details/142411883

(2)调整部分文件夹结构,比如模型归为一类文件夹,这样方便查看模型

(3)检测流程简化,使得人体骨骼关键点实现的摔倒姿态识别代码十分简单,实际只要40多行代码就实现整个检测流程

【效果展示】

【特别注意】

本项目由于使用了3个模型,所以实时性能较差,建议采用GPU推理加快推理速度,同时尽量不要使用cv2.imshow去实时显示窗口,而是采用写出视频结果方式

【测试环境】

代码提供有requirments.txt,但是环境其实比较宽松,比如我的环境是

torch==1.9.0

opencv-python==4.8.0.76

【实现代码】

【原来代码】

detect.py

import argparse
import time
from pathlib import Path
from torch import from_numpy, jitimport cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
import os
import datetime
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, 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_synchronizedimport runOpenposeimport YOLOdef detect(save_img=False):global ipsource, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_sizewebcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(('rtsp://', 'rtmp://', 'http://'))# Directoriessave_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# 加载摔倒检测的模型print("加载摔倒检测的模型开始")net = jit.load(r'action_detect/checkPoint/openpose.jit')action_net = jit.load(r'action_detect/checkPoint/action.jit')print("加载摔倒检测的模型结束")# Initializeset_logging()# 获取设备device = select_device(opt.device)# 如果设备为gpu,使用Float16half = device.type != 'cpu'  # half precision only supported on CUDA# Load model# 加载Float32模型,确保用户设定的输入图片分辨率能整除32(如果不能则调整为能整除并删除)#model = attempt_load(weights, map_location=device)  # load FP32 modelmodel=YOLO.Predictor(weights,device,opt.classes,opt.conf_thres)imgsz = check_img_size(imgsz, s=32)  # !!!check img_size# 设置Float16if half:model.model.half()  # to FP16# Set Dataloader# 通过不同的输入源来设置不同的数据加载方式vid_path, vid_writer = None, Noneif webcam:view_img = Truecudnn.benchmark = True  # set True to speed up constant image size inferencedataset = LoadStreams(source, img_size=imgsz)else:save_img = True# 如果检测视频的时候想显示出来,可以再这里加一行 view_img = Trueview_img = Truedataset = LoadImages(source, img_size=imgsz)# Get names and colors# 获取类别的名字names = model.module.names if hasattr(model, 'module') else model.model.names# 设置画框的颜色colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]# Run inferencet0 = time.time()# 进行一次向前推理,测试程序是否正常img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img_ = model.model(img.half() if half else img) if device.type != 'cpu' else None  # run once"""path 图片/视频路径img 进行resize+pad之后的图片img0 原size图片cap 当读取图片时为None,读取视频时为视频源"""for path, img, im0s, vid_cap in dataset:img = torch.from_numpy(img).to(device)# 图片也设置为Float16img = img.half() if half else img.float()  # uint8 to fp16/32img /= 255.0  # 0 - 255 to 0.0 - 1.0# 没有batch_size 的话则在最前面增加一个轴if img.ndimension() == 3:img = img.unsqueeze(0)# Inferencet1 = time_synchronized()pred=model.predict(source=img)t2 = time_synchronized()# Process detections# 对每一张图片作处理for i, det in enumerate(pred):  # detections per image# 如果输入源是webcam 则batch_size 不为1,取出dataset中的一张图片if webcam:  # batch_size >= 1p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.countelse:p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)# print(det)boxList = []  # 框的一个list 给openpose 使用p = Path(p)  # to Path# 设置保存图片/视频的路径save_path = str(save_dir / p.name)  # img.jpg# 设置保存框最薄txt文件的路径txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # img.txt# 设置打印信息(图片长宽)s += '%gx%g ' % img.shape[2:]  # print stringgn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwhif len(det):# Rescale boxes from img_size to im0 size# 调整预测框的坐标:基于resize+pad的图片的坐标 -->基于原size图片的坐标# 此时坐标格式为xyxydet[:, :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 classs += f'{n} {names[int(c)]}s, '  # add to string# Write results# 保存预测结果for *xyxy, conf, cls in reversed(det):if save_txt:  # Write to file# 将xyxy(左上角+右下角)格式转为xywh(中心点+宽长)格式,并除上w,h做归一化,转化为列表再保存xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywhline = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)  # label formatwith open(txt_path + '.txt', 'a') as f:f.write(('%g ' * len(line)).rstrip() % line + '\n')# 在原图上画框if save_img or view_img:  # Add bbox to imagelabel = f'{names[int(cls)]} {conf:.2f}'plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)boxList.append([int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])])runOpenpose.run_demo(net, action_net, [im0], 256, False, boxList)  # 人体姿态检测 将图片和yolov5检测人体的框也传给openpose# Print time (inference + NMS)# 打印向前传播+nms时间print(f'{s}Done. ({t2 - t1:.3f}s)')if save_img:if dataset.mode == 'image':imageName = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + ".jpg"cv2.imwrite(save_path+imageName, im0)else:  # 'video'if vid_path != save_path:  # new videovid_path = save_pathif isinstance(vid_writer, cv2.VideoWriter):vid_writer.release()  # release previous video writerfourcc = 'mp4v'  # output video codecfps = 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)print('保存图片')# 打印总时间print(f'Done. ({time.time() - t0:.3f}s)')cv2.destroyAllWindows()if __name__ == '__main__':parser = argparse.ArgumentParser()# 选用训练的权重,可用根目录下的yolov5s.pt,也可用runs/train/exp/weights/best.ptparser.add_argument('--weights', type=str, default='models/hub/yolov8s.pt', help='model.pt path(s)')# 检测数据,可以是图片/视频路径,也可以是'0'(电脑自带摄像头),也可以是rtsp等视频流parser.add_argument('--source', type=str, default='0',help='source')  # file/folder, 0 for webcam# 网络输入图片大小parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')# 置信度阈值,检测到的对象属于特定类(狗,猫,香蕉,汽车等)的概率parser.add_argument('--conf-thres', type=float, default=0.5, help='object confidence threshold')# 做nms的iou阈值parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')# 检测的设备,cpu;0(表示一个gpu设备cuda:0);0,1,2,3(多个gpu设备)。值为空时,训练时默认使用计算机自带的显卡或CPUparser.add_argument('--device', default='gpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')# 是否展示检测之后的图片/视频,默认Falseparser.add_argument('--view-img', action='store_true', help='display results')# 是否将检测的框坐标以txt文件形式保存,默认Falseparser.add_argument('--save-txt', action='store_true', help='save results to *.txt')# 是否将检测的labels以txt文件形式保存,默认Falseparser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')# 设置只保留某一部分类别,如0或者0 2 3parser.add_argument('--classes', nargs='+', default=[0,67], type=int,help='filter by class: --class 0, or --class 0 2 3')# 进行nms是否也去除不同类别之间的框,默认Falseparser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')# 推理的时候进行多尺度,翻转等操作(TTA)推理parser.add_argument('--augment', action='store_true', help='augmented inference')# 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为Falseparser.add_argument('--update', action='store_true', help='update all models')# 检测结果所存放的路径,默认为runs/detectparser.add_argument('--project', default='runs/detect', help='save results to project/name')# 检测结果所在文件夹的名称,默认为expparser.add_argument('--name', default='exp', help='save results to project/name')# 若现有的project/name存在,则不进行递增parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')opt = parser.parse_args()print(opt)with torch.no_grad():detect()

我的代码main_video.py

# -*- coding: utf-8 -*-
# Copyright (C) 2024/9/21 FIRC. All Rights Reserved
# @Time    : 2024/9/21 上午8:29
# @Author  : FIRC
# @File    : main.py
# @Software: PyCharm-2024.2
# @ Function Description:
import torch
import numpy as np
from torch import from_numpy, jit
from Yolov8Detector import *
import runOpenpose
import cv2device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 加载摔倒检测的模型
print("加载摔倒检测的模型开始")
net = jit.load(r'weights/openpose.jit', map_location=device)
action_net = jit.load(r'weights/action.jit', map_location=device)
print("加载yolov8模型")
detector = Yolov8Detector()
print('所有模型加载完成!')
video_file = "video/tt.mp4"
save_file = 'result.mp4'
cap = cv2.VideoCapture(video_file)# 获取视频帧速率 FPS
frame_fps = int(cap.get(cv2.CAP_PROP_FPS))
# 获取视频帧宽度和高度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print("video fps={},width={},height={}".format(frame_fps, frame_width, frame_height))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(save_file, fourcc, frame_fps, (frame_width, frame_height))
count = 0while True:ret, frame = cap.read()if not ret:print('read over!')breakcount += 1result_lists = detector.inference_image(frame)for box in result_lists:x = box[4] - box[2]y = box[3] - box[1]if x / y >= 0.8:  # 比例>0.8 可能会是摔倒print('进行人体姿态检测')box_list = [res[2:6] for res in result_lists]runOpenpose.run_demo(net, action_net, [frame], 256, False, box_list)  # 人体姿态检测 将图片和yolov5检测人体的框也传给openposebreak#frame = detector.draw_image(frame,result_list=result_lists)#out.write(frame)print('detected frame {}'.format(count))cv2.imshow('frame',frame)if cv2.waitKey(1) & 0xFF == ord('q'):break
out.release()
cap.release()
cv2.destroyAllWindows()

如果您想把人画上去,请打开注释   

第52行 #frame = detector.draw_image(frame,result_list=result_lists)

如果您保存视频,请打开注释

第53行    #out.write(frame)

【完整源码下载地址】

【延伸扩展】

运行runOpenpose.py
只跑了open pose 可以获得人体的关键点图,用于后续的.jit模型训练 人体的关键点图会保存在data/test中 pose.py中draw方法的最下面可以控制保存关键点图的位置

如果想要检测其他姿势: 1.收集图片,跑runOpenpose.py 文件获得人体的关键点图 2.对人体的关键点图根据自己想要的进行分类放在data/train 和 data/test 3.跑 action_detect/train.py

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

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

相关文章

队列的各种接口的实现(C)

队列的概念 队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头 队列的实…

华为地图服务 - 如何在地图上绘制多边形? -- HarmonyOS自学16

场景介绍 本章节将向您介绍如何在地图上绘制多边形。 接口说明 添加多边形功能主要由MapPolygonOptions、addPolygon和MapPolygon提供,更多接口及使用方法请参见接口文档。 接口名 描述 MapPolygonOptions 用于描述MapPolygon属性。 addPolygon(options: mapC…

(八)使用Postman工具调用WebAPI

访问WebAPI的方法&#xff0c;Postman工具比SoapUI好用一些。 1.不带参数的get请求 [HttpGet(Name "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() {return Enumerable.Range(1, 5).Select(index > new WeatherForecast{Date DateT…

优优嗨聚集团:引领互联网服务新篇章

在当今这个日新月异的互联网时代&#xff0c;企业之间的竞争愈发激烈&#xff0c;如何高效地运营线上业务成为了众多商家关注的焦点。在这一背景下&#xff0c;四川优优嗨聚集团凭借其卓越的服务质量、创新的技术解决方案和强大的品牌影响力&#xff0c;逐渐成为了众多商家信赖…

【大模型教程】如何在Spring Boot中无缝集成LangChain4j,玩转AI大模型!

0 前言 LangChain4j 提供了用于以下功能的 Spring Boot 启动器&#xff1a; 常用集成声明式 AI 服务 1 常用集成的 Spring Boot starters Spring Boot 启动器帮助通过属性创建和配置 语言模型、嵌入模型、嵌入存储 和其他核心 LangChain4j 组件。 要使用 Spring Boot 启动…

基于MATLAB的虫害检测系统

课题背景介绍 中国为农业大国&#xff0c;因此在农业病虫害防治等方面积累了丰富的经验&#xff0c;但在实际工作过程中也存在许多问题。如过于依赖传统经验&#xff0c;对突如而来的新型病虫害问题研究不够到位&#xff0c;如由于判断者主观上面的一些模糊&#xff0c;而带来…

从零实现循环神经网络(二)

#本篇博客代码是基于上一篇《从零实现循环神经网络&#xff08;一&#xff09;》 上一篇网址&#xff1a;从零实现循环神经网络&#xff08;一&#xff09;-CSDN博客 1.初始化时返回隐藏层状态 def init_rnn_state(batch_size, num_hiddens, device):"""bat…

大神用一幅动态的风景画:让天气预报变得更生动

你有没有想过,有一天你可以不看那些冰冷的天气图表,而是通过一幅美丽的风景画就能知道明天的天气?想象一下,清晨醒来,打开手机,看到的不是一堆晦涩的数字,而是一幅阳光洒满草原的画,告诉你今天是个好天气。这就是现在逐渐兴起的一种新方式——通过风景图像来可视化天气…

【网络】高级IO——LT和ET

在上一篇的学习中&#xff0c;我们已经简单的使用了epoll的三个接口&#xff0c;但是仅仅了解那些东西是完全不够的&#xff01;&#xff01;接下来我们将更深入的学习epoll 1.epoll的两种工作模式——LT和ET 下面来举一个例子帮助大家理解ET和LT模式的区别&#xff08;送快递…

内存:生成式AI带来全新挑战与机遇

之前小编也写过多篇AI存储相关的文章&#xff0c;包括AI背景与分层存储的分析&#xff0c;以及AI存储重点从训练转向推理等内容。具体参考&#xff1a; 深度剖析&#xff1a;AI存储架构的挑战与解决方案 存储正式迈入超大容量SSD时代&#xff01; 这可能是最清晰的AI存储数据…

stack和queue(一)

接下来讲解一些stack栈和queue的简单使用 stack的概念 stack是一种容器适配器&#xff0c;专门用在具有后进先出操作的上下文环境中&#xff0c;其删除只能从容器的一端进行 元素的插入与提取操作。 特性是先进先出 后进后出 构造一个栈堆 int main() {deque<int>…

vue项目加载cdn失败解决方法

注释index.html文件中 找到vue.config.js文件注释、

Spring IDEA 2024 自动生成get和set以及toString方法

1.简介 在IDEA中使用自带功能可以自动生成get和set以及toString方法 2.步骤 在目标类中右键&#xff0c;选择生成 选择Getter和Setter就可以生成每个属性对应的set和get方法&#xff0c; 选择toString就可以生成类的toString方法&#xff0c;

快速响应:提升前端页面加载速度技巧的必知策略方案

在本文中&#xff0c;我们将深入探讨导致页面加载缓慢的常见原因&#xff0c;并分享一系列切实可行的优化策略&#xff0c;无论你是刚入门的新手&#xff0c;还是经验丰富的开发者&#xff0c;这些技巧都将帮助你提升网页性能&#xff0c;让你的用户体验畅快无阻。 相信作为前端…

网页与微信小程序:一场轻量化应用的博弈

网页与微信小程序&#xff1a;一场轻量化应用的博弈 在如今的信息时代&#xff0c;移动互联网已然成为主流&#xff0c;而在这一趋势的驱动下&#xff0c;应用形态也在不断演变。微信小程序与传统网页&#xff0c;作为两种不同的应用形态&#xff0c;正如两条并行却又交织的道…

PY+MySQL(等先完成mysql的学习)

第一章&#xff1a;准备工作&#xff08;重点关于mysql&#xff09; win安装 下载&#xff1a; 网址&#xff1a;MySQL :: Download MySQL Community Server版本&#xff1a;我的是8.0&#xff0c;但是建议5.7 下载&#xff1a;安装&#xff0c;因为是zip文件所以直接解压就好了…

2024/9/21 leetcode 21.合并两个有序链表 2.两数相加

目录 21.合并两个有序链表 题目描述 题目链接 解题思路与代码 2.两数相加 题目描述 题目链接 解题思路与代码 --------------------------------------------------------------------------- 21.合并两个有序链表 题目描述 将两个升序链表合并为一个新的 升序 链表并返…

模版结构体没有可用成员(C3203)

没有typedef模版结构体而导致。 并且_tables[index]无法访问HashData内部的成员。

任务管理与守护进程【Linux】

文章目录 进程组前台进程&后台进程守护进程daemon 进程组 组长是多个进程的第一个&#xff0c;组长进程的标识是&#xff0c;其进程组ID等于其进程ID 前台进程&后台进程 前台进程&#xff1a;能获取键盘输入&#xff0c;即拥有键盘文件 后台进程&#xff1a;不能获取…

无人机之激光避障篇

无人机的激光避障技术是通过激光传感器来感知和避开周围障碍物的一种高级技术。以下是关于无人机激光避障技术的详细解析&#xff1a; 一、技术原理 激光避障技术利用激光束的直线传播和反射特性&#xff0c;通过发送激光束并接收反射回来的信号&#xff0c;来检测和计算周围障…