Python玩人工智能:你的仰卧起坐达标了吗?


介绍

Google出了一个开源的、跨平台的、可定制化的机器学习解决方案工具包,给在线流媒体(当然也可以用于普通的视频、图像等)提供了机器学习解决方案。感兴趣的同学可以打开这个网址了解详情:https://mediapipe.dev/。它提供了手势、人体姿势、人脸、物品等识别和追踪功能,并提供了C++、Python、JavaScript等编程语言的工具包以及iOS、Android平台的解决方案,今天我们就来看一下如何使用MediaPipe提供的人体姿势识别功能,使用Python编程完成一个“仰卧起坐检测”的程序。

准备工作

  1. 安装Python3.8.x

  2. 创建一个Python项目,建议使用virtualenv创建一个项目专有的Python环境

  3. 安装包:Opencv-Python、mediapipe、numpy

开始编程

  1. 创建一个人体姿势识别模块,在这个模块中,我们使用mediapipe模块来实现人体姿势识别,并获取姿势数据。

 1 import cv2
 2 import mediapipe as mp
 3 import math
 4 
 5 
 6 class PoseDetector():
 7     '''
 8     人体姿势检测类
 9     '''
10 
11     def __init__(self,
12                  static_image_mode=False,
13                  upper_body_only=False,
14                  smooth_landmarks=True,
15                  min_detection_confidence=0.5,
16                  min_tracking_confidence=0.5):
17         '''
18         初始化
19         :param static_image_mode: 是否是静态图片,默认为否
20         :param upper_body_only: 是否是上半身,默认为否
21         :param smooth_landmarks: 设置为True减少抖动
22         :param min_detection_confidence:人员检测模型的最小置信度值,默认为0.5
23         :param min_tracking_confidence:姿势可信标记的最小置信度值,默认为0.5
24         '''
25         self.static_image_mode = static_image_mode
26         self.upper_body_only = upper_body_only
27         self.smooth_landmarks = smooth_landmarks
28         self.min_detection_confidence = min_detection_confidence
29         self.min_tracking_confidence = min_tracking_confidence
30         # 创建一个Pose对象用于检测人体姿势
31         self.pose = mp.solutions.pose.Pose(self.static_image_mode, self.upper_body_only, self.smooth_landmarks,
32                                            self.min_detection_confidence, self.min_tracking_confidence)
33 
34     def find_pose(self, img, draw=True):
35         '''
36         检测姿势方法
37         :param img: 一帧图像
38         :param draw: 是否画出人体姿势节点和连接图
39         :return: 处理过的图像
40         '''
41         imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
42         # pose.process(imgRGB) 会识别这帧图片中的人体姿势数据,保存到self.results中
43         self.results = self.pose.process(imgRGB)
44         if self.results.pose_landmarks:
45             if draw:
46                 mp.solutions.drawing_utils.draw_landmarks(img, self.results.pose_landmarks,
47                                                           mp.solutions.pose.POSE_CONNECTIONS)
48         return img
49 
50     def find_positions(self, img):
51         '''
52         获取人体姿势数据
53         :param img: 一帧图像
54         :param draw: 是否画出人体姿势节点和连接图
55         :return: 人体姿势数据列表
56         '''
57         # 人体姿势数据列表,每个成员由3个数字组成:id, x, y
58         # id代表人体的某个关节点,x和y代表坐标位置数据
59         self.lmslist = []
60         if self.results.pose_landmarks:
61             for id, lm in enumerate(self.results.pose_landmarks.landmark):
62                 h, w, c = img.shape
63                 cx, cy = int(lm.x * w), int(lm.y * h)
64                 self.lmslist.append([id, cx, cy])
65 
66         return self.lmslist
67 
68     def find_angle(self, img, p1, p2, p3, draw=True):
69         '''
70         获取人体姿势中3个点p1-p2-p3的角度
71         :param img: 一帧图像
72         :param p1: 第1个点
73         :param p2: 第2个点
74         :param p3: 第3个点
75         :param draw: 是否画出3个点的连接图
76         :return: 角度
77         '''
78         x1, y1 = self.lmslist[p1][1], self.lmslist[p1][2]
79         x2, y2 = self.lmslist[p2][1], self.lmslist[p2][2]
80         x3, y3 = self.lmslist[p3][1], self.lmslist[p3][2]
81 
82         # 使用三角函数公式获取3个点p1-p2-p3,以p2为角的角度值,0-180度之间
83         angle = int(math.degrees(math.atan2(y1 - y2, x1 - x2) - math.atan2(y3 - y2, x3 - x2)))
84         if angle < 0:
85             angle = angle + 360
86         if angle > 180:
87             angle = 360 - angle
88 
89         if draw:
90             cv2.circle(img, (x1, y1), 20, (0, 255, 255), cv2.FILLED)
91             cv2.circle(img, (x2, y2), 30, (255, 0, 255), cv2.FILLED)
92             cv2.circle(img, (x3, y3), 20, (0, 255, 255), cv2.FILLED)
93             cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255, 3))
94             cv2.line(img, (x2, y2), (x3, y3), (255, 255, 255, 3))
95             cv2.putText(img, str(angle), (x2 - 50, y2 + 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 255), 2)
96 
97         return angle
  1. 编写situps.py,在这个程序中我们将使用opencv读取视频文件,当然你也可以使用摄像头直接拍摄。调用人体姿势识别模块进行视频中人体姿势识别并获取姿势数据,通过人体姿势中3个位置点的数据:肩膀(11)、臀部(23)、膝盖(25),计算这3个点的角度,判断仰卧起坐是否达标。

# 导入opencv工具包
import cv2
# 导入numpy
import numpy as np
# 导入姿势识别器
from poseutil import PoseDetector

# 打开视频文件
cap = cv2.VideoCapture('videos/situp.mp4')
# 姿势识别器
detector = PoseDetector()

# 方向与个数
dir = 0  # 0为躺下,1为坐起
count = 0

while True:
    # 读取摄像头,img为每帧图片
    success, img = cap.read()
    if success:
        h, w, c = img.shape
        # 识别姿势
        img = detector.find_pose(img, draw=True)
        # 获取姿势数据
        positions = detector.find_positions(img)

        if positions:
            # 获取仰卧起坐的角度
            angle = detector.find_angle(img, 11, 23, 25)
            # 进度条长度
            bar = np.interp(angle, (50, 130), (w // 2 - 100, w // 2 + 100))
            cv2.rectangle(img, (w // 2 - 100, h - 150), (int(bar), h - 100), (0, 255, 0), cv2.FILLED)
            # 角度小于55度认为坐起
            if angle <= 55:
                if dir == 0:
                    count = count + 0.5
                    dir = 1
            # 角度大于120度认为躺下
            if angle >= 120:
                if dir == 1:
                    count = count + 0.5
                    dir = 0
            cv2.putText(img, str(int(count)), (w // 2, h // 2), cv2.FONT_HERSHEY_SIMPLEX, 10, (255, 255, 255), 20, cv2.LINE_AA)

        # 打开一个Image窗口显示视频图片
        cv2.imshow('Image', img)
        
    else:
        # 视频结束退出
        break

    # 如果按下q键,程序退出
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

# 关闭摄像头
cap.release()
# 关闭程序窗口
cv2.destroyAllWindows()

运行测试

总体感觉mediapipe识别率还是很不错的,在使用CPU的情况下基本上能达到25帧/秒。我们可以通过调整仰卧起坐的判断角度来使这个程序更符合你自己的仰卧起坐检测。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM