Python OpenCV实现姿态识别的详细代码
作者:SlowFeather 发布时间:2023-05-27 23:42:31
标签:Python,OpenCV,姿态识别
前言
想要使用摄像头实现一个多人姿态识别
环境安装
下载并安装 Anaconda
官网连接 https://anaconda.cloud/installers
安装 Jupyter Notebook
检查Jupyter Notebook是否安装
Tip:这里涉及到一个切换Jupyter Notebook内核的问题,在我这篇文章中有提到
AnacondaNavigator Jupyter Notebook更换Python内核https://www.jb51.net/article/238496.htm
生成Jupyter Notebook项目目录
打开Anaconda Prompt
切换到项目目录
输入Jupyter notebook
在浏览器中打开 Jupyter Notebook
并创建新的记事本
下载训练库
图片以及训练库都在下方链接
https://github.com/quanhua92/human-pose-estimation-opencv
将图片和训练好的模型放到项目路径中graph_opt.pb
为训练好的模型
单张图片识别
导入库
import cv2 as cv
import os
import matplotlib.pyplot as plt
加载训练模型
net=cv.dnn.readNetFromTensorflow("graph_opt.pb")
初始化
inWidth=368
inHeight=368
thr=0.2
BODY_PARTS = { "Nose": 0, "Neck": 1, "RShoulder": 2, "RElbow": 3, "RWrist": 4,
"LShoulder": 5, "LElbow": 6, "LWrist": 7, "RHip": 8, "RKnee": 9,
"RAnkle": 10, "LHip": 11, "LKnee": 12, "LAnkle": 13, "REye": 14,
"LEye": 15, "REar": 16, "LEar": 17, "Background": 18 }
POSE_PAIRS = [ ["Neck", "RShoulder"], ["Neck", "LShoulder"], ["RShoulder", "RElbow"],
["RElbow", "RWrist"], ["LShoulder", "LElbow"], ["LElbow", "LWrist"],
["Neck", "RHip"], ["RHip", "RKnee"], ["RKnee", "RAnkle"], ["Neck", "LHip"],
["LHip", "LKnee"], ["LKnee", "LAnkle"], ["Neck", "Nose"], ["Nose", "REye"],
["REye", "REar"], ["Nose", "LEye"], ["LEye", "LEar"] ]
载入图片
img = cv.imread("image.jpg")
显示图片
plt.imshow(img)
调整图片颜色
plt.imshow(cv.cvtColor(img,cv.COLOR_BGR2RGB))
姿态识别
def pose_estimation(frame):
frameWidth=frame.shape[1]
frameHeight=frame.shape[0]
net.setInput(cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (127.5, 127.5, 127.5), swapRB=True, crop=False))
out = net.forward()
out = out[:, :19, :, :] # MobileNet output [1, 57, -1, -1], we only need the first 19 elements
assert(len(BODY_PARTS) == out.shape[1])
points = []
for i in range(len(BODY_PARTS)):
# Slice heatmap of corresponging body's part.
heatMap = out[0, i, :, :]
# Originally, we try to find all the local maximums. To simplify a sample
# we just find a global one. However only a single pose at the same time
# could be detected this way.
_, conf, _, point = cv.minMaxLoc(heatMap)
x = (frameWidth * point[0]) / out.shape[3]
y = (frameHeight * point[1]) / out.shape[2]
# Add a point if it's confidence is higher than threshold.
points.append((int(x), int(y)) if conf > thr else None)
for pair in POSE_PAIRS:
partFrom = pair[0]
partTo = pair[1]
assert(partFrom in BODY_PARTS)
assert(partTo in BODY_PARTS)
idFrom = BODY_PARTS[partFrom]
idTo = BODY_PARTS[partTo]
# 绘制线条
if points[idFrom] and points[idTo]:
cv.line(frame, points[idFrom], points[idTo], (0, 255, 0), 3)
cv.ellipse(frame, points[idFrom], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED)
cv.ellipse(frame, points[idTo], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED)
t, _ = net.getPerfProfile()
freq = cv.getTickFrequency() / 1000
cv.putText(frame, '%.2fms' % (t / freq), (10, 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
return frame
# 处理图片
estimated_image=pose_estimation(img)
# 显示图片
plt.imshow(cv.cvtColor(estimated_image,cv.COLOR_BGR2RGB))
视频识别
Tip:与上面图片识别代码是衔接的
视频来自互联网,侵删
cap = cv.VideoCapture('testvideo.mp4')
cap.set(3,800)
cap.set(4,800)
if not cap.isOpened():
cap=cv.VideoCapture(0)
raise IOError("Cannot open vide")
while cv.waitKey(1) < 0:
hasFrame,frame=cap.read()
if not hasFrame:
cv.waitKey()
break
frameWidth=frame.shape[1]
frameHeight=frame.shape[0]
net.setInput(cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (127.5, 127.5, 127.5), swapRB=True, crop=False))
out = net.forward()
out = out[:, :19, :, :] # MobileNet output [1, 57, -1, -1], we only need the first 19 elements
assert(len(BODY_PARTS) == out.shape[1])
points = []
for i in range(len(BODY_PARTS)):
# Slice heatmap of corresponging body's part.
heatMap = out[0, i, :, :]
# Originally, we try to find all the local maximums. To simplify a sample
# we just find a global one. However only a single pose at the same time
# could be detected this way.
_, conf, _, point = cv.minMaxLoc(heatMap)
x = (frameWidth * point[0]) / out.shape[3]
y = (frameHeight * point[1]) / out.shape[2]
# Add a point if it's confidence is higher than threshold.
points.append((int(x), int(y)) if conf > thr else None)
for pair in POSE_PAIRS:
partFrom = pair[0]
partTo = pair[1]
assert(partFrom in BODY_PARTS)
assert(partTo in BODY_PARTS)
idFrom = BODY_PARTS[partFrom]
idTo = BODY_PARTS[partTo]
if points[idFrom] and points[idTo]:
cv.line(frame, points[idFrom], points[idTo], (0, 255, 0), 3)
cv.ellipse(frame, points[idFrom], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED)
cv.ellipse(frame, points[idTo], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED)
t, _ = net.getPerfProfile()
freq = cv.getTickFrequency() / 1000
cv.putText(frame, '%.2fms' % (t / freq), (10, 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
cv.imshow('Video Tutorial',frame)
实时摄像头识别
Tip:与上面图片识别代码是衔接的
cap = cv.VideoCapture(0)
cap.set(cv.CAP_PROP_FPS,10)
cap.set(3,800)
cap.set(4,800)
if not cap.isOpened():
cap=cv.VideoCapture(0)
raise IOError("Cannot open vide")
while cv.waitKey(1) < 0:
hasFrame,frame=cap.read()
if not hasFrame:
cv.waitKey()
break
frameWidth=frame.shape[1]
frameHeight=frame.shape[0]
net.setInput(cv.dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (127.5, 127.5, 127.5), swapRB=True, crop=False))
out = net.forward()
out = out[:, :19, :, :] # MobileNet output [1, 57, -1, -1], we only need the first 19 elements
assert(len(BODY_PARTS) == out.shape[1])
points = []
for i in range(len(BODY_PARTS)):
# Slice heatmap of corresponging body's part.
heatMap = out[0, i, :, :]
# Originally, we try to find all the local maximums. To simplify a sample
# we just find a global one. However only a single pose at the same time
# could be detected this way.
_, conf, _, point = cv.minMaxLoc(heatMap)
x = (frameWidth * point[0]) / out.shape[3]
y = (frameHeight * point[1]) / out.shape[2]
# Add a point if it's confidence is higher than threshold.
points.append((int(x), int(y)) if conf > thr else None)
for pair in POSE_PAIRS:
partFrom = pair[0]
partTo = pair[1]
assert(partFrom in BODY_PARTS)
assert(partTo in BODY_PARTS)
idFrom = BODY_PARTS[partFrom]
idTo = BODY_PARTS[partTo]
if points[idFrom] and points[idTo]:
cv.line(frame, points[idFrom], points[idTo], (0, 255, 0), 3)
cv.ellipse(frame, points[idFrom], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED)
cv.ellipse(frame, points[idTo], (3, 3), 0, 0, 360, (0, 0, 255), cv.FILLED)
t, _ = net.getPerfProfile()
freq = cv.getTickFrequency() / 1000
cv.putText(frame, '%.2fms' % (t / freq), (10, 20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
cv.imshow('Video Tutorial',frame)
参考
DeepLearning_by_PhDScholar
Human Pose Estimation using opencv | python | OpenPose | stepwise implementation for beginners
https://www.youtube.com/watch?v=9jQGsUidKHs
来源:https://blog.csdn.net/a71468293a/article/details/123011891


猜你喜欢
- 在python中常看到在定义函数是使用@func. 这就是装饰器, 装饰器是把一个函数作为参数的函数,常常用于扩展已有函数,即不改变当前函数
- 前言:record类型,这是一种新引用类型,而不是类或结构。record与类不同,区别在于record类型使用基于值的相等性。例如:publ
- 一.请求后台的时候,服务端对每一个请求都会验证权限,而前端也需要对服务器返回的特殊状态码统一处理,所以可以针对业务封装请求。首先我们通过re
- 毫无疑问,Google是当今世界上最成功的互联网公司之一,但是Google也曾推出过一些失败的实验品。还记得Google Accelerat
- 重装了笔记本上的oracle,安装完成后,可以正常使用OEM控制台,但是注销后重新登录或者重启系统后登录,或者笔记本使用网络环境发生了变化,
- 1、引言小 * 丝:鱼哥,你说咱们发快递时填写的地址信息,到后台怎么能看清楚写的对不对呢?小鱼:这种事情还要问? 你没在电商行业混过??小 * 丝:
- 找到自己的mysql数据库的安装位置,如下 C:\Program Files\MySQL\MySQL Server 5.1,在它里面有个的m
- 问题背景查询MySQL中用逗号分隔的字段【a,b,c】是否包含【a】场景模拟现有表【ec_logicplace】,如下图所示:要求判断数值【
- 方式1:在pygame中使用pygame.event.get()方法捕获键盘事件,使用这个方式捕获的键盘事件必须要是按下再弹起才算一次。示例
- 今天刷《剑指offer》的时候碰到这样一道题:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵
- 本文实例讲述了Joomla开启SEF的方法。分享给大家供大家参考,具体如下:使用SEF(search engine friendly)网址的
- 这里分享一个常用的价格格式化的一个方法,在电商的价格处理中非常的实用,我们可以看一个效果这里在价格数据的地方使用了一个过滤器,通过这个过滤器
- python 将字典写为json文件字典结构如下res = { "data":[]}temp
- “高并发和多线程”总是被一起提起,给人感觉两者好像相等,实则 高并发 ≠ 多线程多线程是完成任务的一种方法,高并发是系统运行的一种状态,通过
- slice 可以用来获取数组片段,它返回新数组,不会修改原数组。除了正常用法,slice 经常用来将 array-like 对象转换为 tr
- 前言今天来聊一下PyTorch中的torch.nn.Parameter()这个函数,笔者第一次见的时候也是大概能理解函数的用途,但是具体实现
- 本文实例讲述了Python实现两个list求交集,并集,差集的方法。分享给大家供大家参考,具体如下:在python中,数组可以用list来表
- 我们准备如下两个表,并插入数据。#分类CREATE TABLE IF NOT EXISTS `type` (`id` INT(10) UNS
- 本文实例讲述了Python通过递归遍历出集合中所有元素的方法。分享给大家供大家参考。具体实现方法如下:''''
- 一.什么是事务在MySQL中的事务(Transaction)是由存储引擎实现的,在MySQL中,只有InnoDB存储引擎才支持事务。事务处理