Python OpenCV实现姿态识别的详细代码

 更新时间:2022年02月23日 11:39:33   作者:SlowFeather  
这篇文章主要介绍了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

到此这篇关于Python OpenCV实现姿态识别的文章就介绍到这了,更多相关Python姿态识别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中的文件和目录操作实现代码

    Python中的文件和目录操作实现代码

    对于文件和目录的处理,虽然可以通过操作系统命令来完成,但是Python语言为了便于开发人员以编程的方式处理相关工作,提供了许多处理文件和目录的内置函数。重要的是,这些函数无论是在Unix、Windows还是Macintosh平台上,它们的使用方式是完全一致的。
    2011-03-03
  • Python查看已安装包的版本号的多种方法

    Python查看已安装包的版本号的多种方法

    很多朋友一直使用pip list来查询,但如果想知道单个,应该怎么使用呢,在Python中,可以使用多种方法来查看已安装包的版本号,本文给大家详细介绍了Python查看已安装包的版本号的多种方法,需要的朋友可以参考下
    2024-02-02
  • Numpy 多维数据数组的实现

    Numpy 多维数据数组的实现

    这篇文章主要介绍了Numpy 多维数据数组的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • Python中loguru日志库的使用

    Python中loguru日志库的使用

    本文主要介绍了Python中loguru日志库的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • Python使用PIL.image保存图片

    Python使用PIL.image保存图片

    PIL库支持图像存储、显示和处理,它能够处理几乎所有图片格式,可以完成对图像的缩放、剪裁、叠加以及向图像添加线条、图像和文字等操作,下面这篇文章主要给大家介绍了关于Python使用PIL.image保存图片的相关资料,需要的朋友可以参考下
    2022-12-12
  • 图文详解python安装Scrapy框架步骤

    图文详解python安装Scrapy框架步骤

    在本篇内容中我们给大家整理了关于python安装Scrapy框架的图文详细步骤,需要的朋友们跟着学习下。
    2019-05-05
  • python实现防截图的6种方法详解

    python实现防截图的6种方法详解

    防截图是指一组技术或方法,用于防止他人在未经允许的情况下在屏幕上截取或记录图像,这是一个重要的安全措施,它可以防止窃取敏感信息或监视个人信息,本文为大家整理了6种python可以防截图的方法,需要的可以参考下
    2023-10-10
  • Python写的英文字符大小写转换代码示例

    Python写的英文字符大小写转换代码示例

    这篇文章主要介绍了Python写的英文字符大小写转换代码示例,本文例子相对简单,本文直接给出代码实例,需要的朋友可以参考下
    2015-03-03
  • 简单分析python的类变量、实例变量

    简单分析python的类变量、实例变量

    在本篇文章中小编给大家整理的是关于python类变量、实例变量的知识点内容,有需要的朋友们可以学习下。
    2019-08-08
  • Python OS模块实例详解

    Python OS模块实例详解

    这篇文章主要介绍了Python OS模块,结合实例形式总结分析了Python使用OS解析文件路径、判断文件、目录等相关操作技巧,需要的朋友可以参考下
    2019-04-04

最新评论