Python OpenCV实现姿态识别

本文介绍了如何使用Python和OpenCV进行人体姿态识别,包括环境安装(Anaconda和Jupyter Notebook)、训练库下载、单张图片识别流程、视频和摄像头实时识别,并提供了相关资源链接。

前言

想要使用摄像头实现一个多人姿态识别

环境安装

下载并安装 Anaconda

官网连接 https://anaconda.cloud/installers
下载 anaconda nucleus

安装 Jupyter Notebook

检查Jupyter Notebook是否安装
检查Jupyter Notebook是否安装

Tip:这里涉及到一个切换Jupyter Notebook内核的问题,在我这篇文章中有提到
AnacondaNavigator Jupyter Notebook更换Python内核https://blog.csdn.net/a71468293a/article/details/122992170

生成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)
if not cap.isOpened():
    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)
if not cap.isOpened():
    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)

参考

  1. DeepLearning_by_PhDScholar
    Human Pose Estimation using opencv | python | OpenPose | stepwise implementation for beginners
    https://www.youtube.com/watch?v=9jQGsUidKHs
<think>好的,我需要帮助用户使用PythonOpenCV实现姿态识别。首先,我得回顾一下用户的问题和提供的引用内容。用户提到了引用[3]和[4],其中引用[4]特别提到了使用Mediapipe库进行人体姿态检测,这应该是一个关键点。用户希望用OpenCVPython姿态识别,但OpenCV本身可能没有现成的姿态检测模型,所以可能需要结合其他库。比如Mediapipe,这是Google的一个开源框架,专门用于人体姿态、手部跟踪等。引用[4]里确实提到了Mediapipe,所以这应该是正确的方向。 接下来,我需要考虑实现的步骤。首先,安装必要的库,比如opencv-python和mediapipe。然后,使用Mediapipe提供的姿态检测模型,初始化模块,读取视频流或图像,进行检测并绘制关键点。可能需要分步骤说明:环境准备、初始化模型、处理图像/视频、提取关键点并可视化。还要注意代码示例的正确性,确保用户能直接复制运行。同时,要解释关键参数,比如static_image_mode和min_detection_confidence,这样用户能理解如何调整检测的灵敏度和准确性。 另外,用户可能想知道如何计算角度或进行进一步的动作分析,比如引用[4]提到的计算角度,这部分可以作为扩展内容,但基础教程需要先完成关键点检测。可能还要提到实时摄像头处理的注意事项,比如循环读取帧,释放资源等。 最后,生成相关问题,帮助用户深入学习和解决问题,比如性能优化、与其他库的整合、特定动作识别等。要确保引用正确,比如引用[4]在涉及角度计算时提到,但基础实现可能不需要,所以只在扩展部分引用。</think>### Python+OpenCV实现姿态识别的方法教程 姿态识别是计算机视觉中的重要应用,结合OpenCV和**Mediapipe**库可实现高效的人体关键点检测。以下是详细步骤: --- #### 一、环境准备 1. 安装依赖库: ```bash pip install opencv-python mediapipe numpy ``` --- #### 二、初始化姿态检测模型 ```python import cv2 import mediapipe as mp # 初始化Mediapipe姿态检测模块 mp_pose = mp.solutions.pose pose = mp_pose.Pose( static_image_mode=False, # 适用于视频流(True为静态图片) min_detection_confidence=0.5, # 检测置信度阈值 min_tracking_confidence=0.5 # 跟踪置信度阈值 ) mp_drawing = mp.solutions.drawing_utils # 用于绘制关键点 ``` --- #### 三、处理图像/视频流 1. **单张图片识别**: ```python image = cv2.imread("input.jpg") image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 转换为RGB格式 # 执行姿态检测 results = pose.process(image_rgb) # 绘制关键点和连接线 if results.pose_landmarks: mp_drawing.draw_landmarks( image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS, landmark_drawing_spec=mp_drawing.DrawingSpec(color=(0,255,0), thickness=2) ) cv2.imshow("Output", image) cv2.waitKey(0) ``` 2. **实时摄像头识别**: ```python cap = cv2.VideoCapture(0) while cap.isOpened(): ret, frame = cap.read() if not ret: break frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = pose.process(frame_rgb) if results.pose_landmarks: mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS) cv2.imshow("Pose Detection", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` --- #### 四、关键数据结构解析 - `results.pose_landmarks`包含33个人体关键点坐标(归一化值)[^4],例如: - 0号点:鼻子 - 11号点:左肩 - 15号点:左手腕 - 可通过以下代码获取坐标的实际像素值: ```python h, w, _ = image.shape for landmark in results.pose_landmarks.landmark: x_px = int(landmark.x * w) y_px = int(landmark.y * h) ``` --- #### 五、扩展功能(动作分析) 结合关键点坐标可实现动作分类,例如计算手臂角度: ```python # 以左肘为例(关键点11-13-15) shoulder = [landmarks[11].x, landmarks[11].y] elbow = [landmarks[13].x, landmarks[13].y] wrist = [landmarks[15].x, landmarks[15].y] # 向量计算 vec1 = np.array([shoulder[0]-elbow[0], shoulder[1]-elbow[1]]) vec2 = np.array([wrist[0]-elbow[0], wrist[1]-elbow[1]]) cos_angle = np.dot(vec1, vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2)) angle = np.arccos(cos_angle) * 180 / np.pi # 角度值[^4] ``` ---
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值