python俯卧撑计数代码

360影视 2025-01-29 22:03 2

摘要:import cv2import mediapipe as mpimport numpy as np# 初始化 MediaPipe Posemp_pose = mp.solutions.posemp_drawing = mp.solutions.drawing

这里主要是用到了MediaPipe库,对于标准的俯卧撑还是统计比较准确的

import cv2import mediapipe as mpimport numpy as np# 初始化 MediaPipe Posemp_pose = mp.solutions.posemp_drawing = mp.solutions.drawing_utils # 画图工具pose = mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5)# 计算角度函数def calculate_angle(a, b, c): """ 计算由点 a, b, c 形成的角度 (b 是顶点) """ a = np.array([a.x, a.y]) # 第一个关键点 b = np.array([b.x, b.y]) # 顶点 c = np.array([c.x, c.y]) # 第二个关键点 ba = a - b bc = c - b cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) angle = np.arccos(np.clip(cosine_angle, -1.0, 1.0)) return np.degrees(angle)# 读取摄像头# cap = cv2.VideoCapture(0)cap = cv2.VideoCapture("e:/ff.mp4")pushup_count = 0in_position = None # 初始状态设为 None,确保第一下能正确计数while cap.isOpened: ret, frame = cap.read if not ret: break # 反转镜像 frame = cv2.flip(frame, 1) # 转换为 rgb rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) results = pose.process(rgb_frame) # 获取骨架关键点 if results.pose_landmarks: landmarks = results.pose_landmarks.landmark # 画出关键点和骨架 mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS, mp_drawing.DrawingSpec(color=(0, 0, 255), thickness=2, circle_radius=3), mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2)) # 获取肩部、肘部、手腕坐标 left_shoulder = landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER] left_elbow = landmarks[mp_pose.PoseLandmark.LEFT_ELBOW] left_wrist = landmarks[mp_pose.PoseLandmark.LEFT_WRIST] # 计算左手肘角度 left_elbow_angle = calculate_angle(left_shoulder, left_elbow, left_wrist) # 俯卧撑计数逻辑(修正第一下计数) if in_position is None: # 第一次检测到角度时,设置基准状态 in_position = left_elbow_angle 160 and in_position: # 伸直手臂,回到起始位置,完成一次 pushup_count += 1 in_position = False # 在画面上显示计数 cv2.putText(frame, f'Push-ups: {pushup_count}', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # 显示画面 cv2.imshow("Push-up Counter", frame) # 按 'Esc' 退出 if cv2.waitKey(1) & 0xFF == 27: # 27 是 ESC 的 ASCII 码 break# 释放资源cap.releasecv2.destroyAllWindows

来源:新手村养牛

相关推荐