开始使用

使用 Ultralytics YOLO26 监测锻炼

Open Workouts Monitoring In Colab

通过 Ultralytics YOLO26 进行姿态估计来监控锻炼,可以实时准确跟踪身体关键点和关节,从而改进运动评估。这项技术能即时反馈运动姿势、跟踪锻炼计划并衡量表现指标,帮助用户和教练优化训练课程。



观看: 如何使用 Ultralytics YOLO 监测健身训练动作 | 深蹲、腿部伸展、俯卧撑等

锻炼监测的优势#

  • 优化表现:根据监测数据调整锻炼计划,以取得更好的效果。
  • 实现目标:跟踪并调整健身目标,取得可量化的进展。
  • 个性化:根据个人数据定制锻炼计划,提升训练效果。
  • 健康意识:及早发现可能表明健康问题或过度训练的模式。
  • 明智决策:根据数据调整锻炼计划并设定切合实际的目标。

实际应用#

锻炼监测锻炼监测
使用姿态估计统计 YOLO 俯卧撑次数使用姿态估计统计 YOLO 引体向上次数
俯卧撑计数引体向上计数

使用 YOLO26 监测锻炼#

AIGym 解决方案使用姿态估计和诸如 YOLO26n-pose 这样的模型运行,通过测量肢体在 up_angle 和 down_angle 阈值之间移动时三个关键点形成的角度来计算重复次数。使用 kpts 选择要跟踪的锻炼动作对应的关键点,然后通过 Python API 或 CLI 在视频上运行该解决方案。

使用 Ultralytics YOLO 监测锻炼
# Run a workout example
yolo solutions workout show=True

# Pass a source video
yolo solutions workout source="path/to/video.mp4"

# Use keypoints for pushups
yolo solutions workout kpts="[6, 8, 10]"

关键点图#

YOLO 姿态估计关键点顺序示意图

AIGym 参数#

下面是 AIGym 参数表:

参数类型默认值说明
modelstrNoneUltralytics YOLO 模型文件的路径。
up_anglefloat145.0“向上”姿势的角度阈值。
down_anglefloat90.0“向下”姿势的角度阈值。
kptslist[int][6, 8, 10]用于监测锻炼动作的三个关键点索引组成的列表。这些关键点对应身体关节或部位,例如肩部、肘部和手腕,可用于俯卧撑、引体向上、深蹲和腹部锻炼等动作。
line_widthint2解决方案绘制的框、关键点和计数的线条粗细。
verboseboolTrue启用逐帧日志,记录输入形状、类别计数和处理速度。跟踪调用本身始终不会输出日志。

AIGym 解决方案还支持一系列对象跟踪参数:

参数类型默认值说明
trackerstr'tracktrack.yaml'指定要使用的跟踪算法。内置选项:botsort.yaml、bytetrack.yaml、ocsort.yaml、deepocsort.yaml、fasttrack.yaml、tracktrack.yaml。
conffloat0.25设置检测的置信度阈值;较低的值允许跟踪更多物体,但可能会包含误检。
ioufloat0.5设置用于筛除重叠检测结果的交并比 (IoU) 阈值。
classeslistNone按类别索引筛选结果。例如,classes=[0, 2, 3] 只跟踪指定类别。
devicestrNone指定推理设备(例如 cpu、cuda:0 或 0)。用户可以选择 CPU、特定 GPU 或其他计算设备来运行模型。
imgszint or tuple640目标推理图像尺寸:正方形图像使用整数,或使用 (height, width) 对。图像尺寸会调整为模型步幅的整数倍。
max_detint300跟踪前每帧保留的最大检测数量,用于限制解决方案在密集场景中处理的物体数量。
quantizeint or strNone推理精度:对于非 CPU 上运行的 PyTorch 和 TorchScript 模型,使用 16 (FP16) 或 32/unset (FP32) 进行选择;其他格式使用其模型文件和运行时所选的精度。此参数替代已弃用的 half 参数。

此外,还可以应用以下可视化设置:

参数类型默认值说明
showboolFalse如果 True,则在窗口中显示带标注的图像或视频。适用于在开发或测试期间即时查看结果。
show_labelsboolTrue在可视化输出中显示每个检测结果的标签,便于立即了解检测到的对象。

常见问题#

  • 要使用 Ultralytics YOLO26 监控锻炼,你可以利用姿态估计功能实时跟踪和分析身体关键点及关节。这样你就能即时获得运动姿势反馈、统计重复次数并衡量表现指标。你可以先使用下面提供的俯卧撑、引体向上或腹部锻炼示例代码:

    import cv2
    
    from ultralytics import solutions
    
    cap = cv2.VideoCapture("path/to/video.mp4")
    assert cap.isOpened(), "Error reading video file"
    w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
    
    gym = solutions.AIGym(
        line_width=2,
        show=True,
        kpts=[6, 8, 10],
    )
    
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or processing is complete.")
            break
        results = gym(im0)
    
    cap.release()
    cv2.destroyAllWindows()
  • 使用 Ultralytics YOLO26 进行锻炼监测有以下几项主要好处:

    • 优化表现:根据监测数据调整锻炼计划,取得更好的效果。
    • 实现目标:轻松跟踪并调整健身目标,取得可量化的进展。
    • 个性化:根据个人数据获取定制的锻炼计划,达到最佳效果。
    • 健康意识:及早发现可能表明存在健康问题或过度训练的模式。
    • 明智决策:根据数据调整锻炼计划并设定切合实际的目标。

    你可以观看 YouTube 视频演示,了解这些优势如何发挥作用。

  • Ultralytics YOLO26 姿态模型能够实时准确跟踪身体关键点和关节,为运动姿势和重复次数提供可靠反馈。实际准确率还取决于摄像头角度、光照、遮挡情况,以及针对每项锻炼选择合适的 kpts、up_angle 和 down_angle 值。

  • 可以,Ultralytics YOLO26 可适配自定义锻炼计划。AIGym 类使用 up_angle、down_angle 和 kpts 参数检测运动重复次数。你可以指定关键点和角度来检测特定锻炼动作。下面是一个配置示例:

    from ultralytics import solutions
    
    gym = solutions.AIGym(
        line_width=2,
        show=True,
        kpts=[6, 8, 10],  # 用于俯卧撑,也可以自定义为其他锻炼
    )

    这种灵活性让你能够监控各种锻炼,并根据健身目标自定义计划。

  • 要保存锻炼监测输出,你可以修改代码,加入一个用于保存处理后帧的视频写入器。示例如下:

    import cv2
    
    from ultralytics import solutions
    
    cap = cv2.VideoCapture("path/to/video.mp4")
    assert cap.isOpened(), "Error reading video file"
    w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
    
    video_writer = cv2.VideoWriter("workouts.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    
    gym = solutions.AIGym(
        line_width=2,
        show=True,
        kpts=[6, 8, 10],
    )
    
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or processing is complete.")
            break
        results = gym(im0)
        video_writer.write(results.plot_im)
    
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()

    此配置会将监测视频写入输出文件,方便你之后回顾锻炼表现,或分享给教练以获取更多反馈。

评论41

提出问题、分享结果,或帮助其他人。

  1. 流川疯

    May I ask how to obtain the value of step and perform some logical operations, such as counting to 10 times for pop-up reminders,many thanks

    1
    1. Glenn JocherUltralytics(已编辑)

      @wynshiter the AIGym solution counts repetitions for you: call results = gym_object(frame) and read results.workout_count (one entry per tracked person). Add your own logic on top, for example if any(c >= 10 for c in results.workout_count): to trigger a pop-up reminder. For further details, please refer to the documentation on workouts monitoring.

    2. nel-mvGitHub

      Thanks for your answer, Glenn. And the documentation on workouts monitoring is just this same page (https://docs.ultralytics.com/guides/workouts-monitoring) we are commenting on?

      And from the comments you gave above, we know that we can get the angles from the gym object: im0, angle_data = gym_object.start_counting(im0, results)

      I was expecting we could get the 'step' value similarly via a return variable.

      Do you know where we could see a list of return variables that the gym object gives?

    3. Glenn JocherUltralytics(已编辑)

      The AIGym results provide workout_count, workout_stage and workout_angle for each tracked person (results = gym_object(frame)), so repetitions are counted for you. To act on them, add your own logic in your processing loop, for example when workout_count reaches a target. For further details, please refer to the Workouts Monitoring documentation.

    4. Glenn JocherUltralytics(已编辑)

      @DanishkhanOp the pose model (yolo26n-pose.pt by default) is downloaded automatically the first time AIGym is initialized, or you can download it manually from the Ultralytics YOLO26 Model Documentation. You can also specify model="yolo26n-pose.pt" in your AIGym() constructor as shown in the workout monitoring examples.

  2. AhmedMostafa3mGitHub

    hello, i guess i came a little late , it ssems that start_counting method is not available any more i want to know how can i use the code above after updating. results = model.predict(frame, verbose=False) frame = gym_object.start_counting(frame, results) thanks alot

    1. Glenn JocherUltralytics(已编辑)

      @AhmedMostafa3m start_counting has been replaced: the solution is now called directly on the frame and runs pose tracking itself, so no separate model.track call is needed:

      from ultralytics import solutions
      
      gym = solutions.AIGym(model="yolo26n-pose.pt")  # Initialize once
      results = gym(frame)
      frame = results.plot_im

      For full implementation details, see the AIGym documentation.

    1. Glenn JocherUltralytics(已编辑)

      @DanishkhanOp the pose estimation model is used automatically when you initialize the AIGym class as shown in the code examples. By default it is yolo26n-pose.pt, which you can also set with model="yolo26n-pose.pt" in your solutions.AIGym() call; it will be downloaded from our servers if not already cached. For more details on pose models, visit our Keypoint Estimation Docs.

  3. AdadAlShababGitHub

    Hi. Suppose I'm detecting the angle between [8, 6, 12] and I wanna show text something like: "The angle between Shoulder and Wrist : {detected angle}" using cv2.putText. How3 can I do that?

    1. Glenn JocherUltralytics

      @AdadAlShabab to display the angle using cv2.putText, you can calculate the angle between the keypoints and then overlay the text on the image. Here's a minimal example:

      import cv2
      import numpy as np
      
      # Assuming you have the coordinates of the keypoints
      shoulder = np.array([x1, y1])
      elbow = np.array([x2, y2])
      wrist = np.array([x3, y3])
      
      # Calculate the angle
      angle = np.degrees(np.arctan2(wrist[1] - elbow[1], wrist[0] - elbow[0]) - 
                         np.arctan2(shoulder[1] - elbow[1], shoulder[0] - elbow[0]))
      
      # Display the angle
      cv2.putText(im0, f"Angle: {angle:.2f}", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

      This will show the angle between the shoulder, elbow, and wrist on your video frame. Adjust the coordinates and text position as needed.

      1
    2. AdadAlShababGitHub

      Hi Glenn. Thanks for your wonderful reply. Can you please tell the about the keypoints [x1, y1]? Like : "shoulder = np.array([x1, y1]) elbow = np.array([x2, y2]) wrist = np.array([x3, y3]" What values should I put here?

    3. Glenn JocherUltralytics

      @AdadAlShabab to determine the values for keypoints like [x1, y1], you need to extract them from the model's output. When you run the model, it provides coordinates for each keypoint. For example, results[0].keypoints will give you the keypoints, and you can access specific ones using their indices. Adjust these based on your specific use case.

    4. AdadAlShababGitHub

      This code: " if result[0].keypoints is not None: keypoints = result[0].keypoints.data.cpu().numpy() # Access the actual keypoints data

                      # Debugging: Print keypoints shape to understand the issue
                      print(f"Keypoints shape: {keypoints.shape}")"

      Providing me results for each frame: 0: 384x640 1 person, 45.3ms Speed: 2.0ms preprocess, 45.3ms inference, 0.0ms postprocess per image at shape (1, 3, 384, 640) Keypoints shape: (1, 17, 3) Person keypoints shape: (17, 3) Keypoint 0: (x=1086.50, y=456.84), Confidence=0.97 Keypoint 1: (x=1098.32, y=446.95), Confidence=0.95 Keypoint 2: (x=1077.20, y=450.47), Confidence=0.90 Keypoint 3: (x=1121.03, y=453.73), Confidence=0.87 Keypoint 4: (x=1068.29, y=461.00), Confidence=0.64 Keypoint 5: (x=1147.66, y=499.11), Confidence=0.99 Keypoint 6: (x=1054.84, y=529.72), Confidence=0.98 Keypoint 7: (x=1192.78, y=521.58), Confidence=0.98 Keypoint 8: (x=1061.91, y=577.40), Confidence=0.90 Keypoint 9: (x=1161.27, y=528.25), Confidence=0.95 Keypoint 10: (x=1100.56, y=558.10), Confidence=0.86 Keypoint 11: (x=1189.49, y=611.80), Confidence=0.99 Keypoint 12: (x=1134.91, y=632.54), Confidence=0.98 Keypoint 13: (x=1234.99, y=644.81), Confidence=0.97 Keypoint 14: (x=1194.94, y=665.07), Confidence=0.94 Keypoint 15: (x=1295.68, y=737.43), Confidence=0.88 Keypoint 16: (x=1300.56, y=750.85), Confidence=0.85

      Are these the values you were talking about?

    5. Glenn JocherUltralytics(已编辑)

      Yes, those are the keypoint values. You can use them to calculate angles between specific joints. For example, use the coordinates of keypoints 8 (elbow), 6 (shoulder), and 12 (hip) to compute the angle and display it with cv2.putText. If you need further assistance, feel free to ask!

  4. actionTurtleGitHub

    If I wanted to count how many steps you took running. Would you just set the pose type to "running"? Or do I need to make my own model for running? Thank you

    1. Glenn JocherUltralytics

      @actionTurtle to count steps for running, you'll need to customize the model since "running" isn't a predefined pose type like "pushup" or "pullup." You can adapt the existing model by training it with running-specific keypoints. For more details, please refer to the workouts monitoring guide.

    2. actionTurtleGitHub

      "You can adapt the existing model by training it with running-specific keypoints."

      Sorry, I still don't understand. Is there a walk though of how I would do that?

    3. Glenn JocherUltralytics

      @actionTurtle to create a custom model for running, you'll need to train it with running-specific keypoints. Unfortunately, there's no built-in "running" pose type, so you'll need to gather a dataset of running poses and train the model accordingly. For a detailed guide on training custom models, please refer to the Ultralytics documentation.

  5. AdadAlShababGitHub

    Hi. The model is working pretty fine. But when I'm running the python file the detected angle data are shown in box. But I want to have the data stored in variable or maybe a list so that I can use them use outside or print in console. Please help.

    1. Glenn JocherUltralytics(已编辑)

      @AdadAlShabab to store the detected angle data in a list, read workout_angle from the results the solution returns for each frame. Here's a basic example:

      import cv2
      
      from ultralytics import solutions
      
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      
      gym_object = solutions.AIGym(model="yolo26n-pose.pt", kpts=[6, 8, 10], show=True)
      
      angles = []
      
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              break
          results = gym_object(im0)
          angles.append(results.workout_angle)  # one angle per tracked person
      
      cap.release()
      cv2.destroyAllWindows()
      print(angles)

      This will store the angle data in the angles list for further use.

      2
    2. AdadAlShababGitHub

      Hi. I want detect angle of two hands simultaneously. So I wrote the code : gym_object = solutions.AIGym( line_thickness=2, view_img=True, pose_type="pushup", kpts_to_check={[8, 6, 12,],[5, 7, 9]}, )

      But it giving me error: TypeError: unhashable type: 'list'

      How to solve? Please let me know. TIA

    3. Glenn JocherUltralytics(已编辑)

      kpts must be a flat list of three keypoint indices, written with square brackets, for example kpts=[6, 8, 10]. Curly braces raise the "unhashable type" error, and nested lists such as [[8, 6, 12], [5, 7, 9]] are not supported. To track two sets of keypoints, create one AIGym instance for each:

      gym_left = solutions.AIGym(kpts=[5, 7, 9])
      gym_right = solutions.AIGym(kpts=[6, 8, 10])
    4. AdadAlShababGitHub

      Hi Glenn! Still it throwing error: im0 = gym_object.start_counting(im0, results) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Bass fish streamlit.venv\Lib\site-packages\ultralytics\solutions\ai_gym.py", line 85, in start_counting k[int(self.kpts_to_check[0])].cpu(), ^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'

    5. Glenn JocherUltralytics(已编辑)

      The error occurs because kpts should be a flat list of three integers, not nested lists. To track both hands, create a separate AIGym instance for each set of keypoints and run both on every frame. If you need further assistance, please check the latest documentation or update your package to the latest version.

    1. Glenn JocherUltralytics

      @Shengguang-Zhou yes, you can train extra classes for pose prediction by customizing the AIGym class and specifying the keypoints and angles for the exercises you want to monitor. For more details, please refer to the Workouts Monitoring Guide.

  6. MarserHKGitHub

    Hello, I would like to ask if there are any examples of using YOLOv8 for behavior recognition in electrical power field scenarios?

    1. Glenn JocherUltralytics

      @MarserHK currently, we don't have specific examples for behavior recognition in electrical power field scenarios. However, you can adapt the pose estimation capabilities of YOLOv8 for such tasks by training on relevant datasets. For more details on pose estimation, you can refer to the workouts monitoring guide here.

  7. duncanwaughGitHub

    Hello, it seems like it has to be setup for a specific type of workout eg. pushups and then it would track pushups, but if you started squatting it wouldn't track your squats. I'm curious if there is a way where U can have a live video feed where lets say you do 10 pushups, then 10 pullups, it will identify how its a different exercise and count it. Thanks.

    1. Glenn JocherUltralytics(已编辑)

      Hello,

      Thank you for your insightful question! You're correct that the current setup of the AIGym solution in Ultralytics YOLOv8 is designed to track specific types of workouts like pushups, pullups, and ab workouts individually. However, your idea of dynamically identifying and counting different exercises in a single session is quite intriguing and can be approached with some modifications.

      Dynamic Workout Detection and Counting

      To achieve dynamic detection and counting of different exercises, you would need to implement a mechanism that can:

      1. Identify the type of exercise being performed: This could be done by analyzing the keypoint movements and angles to classify the exercise type.
      2. Switch the counting logic based on the identified exercise: Once the exercise type is identified, the corresponding counting logic can be applied.

      Here's a conceptual approach to get you started:

      1. Exercise Classification: Use a simple heuristic or a machine learning model to classify the exercise based on keypoint movements.
      2. Dynamic Counting: Switch between different AIGym configurations based on the classified exercise.
      Example Code

      Below is a basic example to illustrate this concept. Note that this is a starting point and may require further refinement based on your specific requirements.

      import cv2
      from ultralytics import YOLO, solutions
      
      # Load the pose estimation model
      model = YOLO("yolo26n-pose.pt")
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
      
      # Initialize video writer if needed
      video_writer = cv2.VideoWriter("workouts.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
      
      # Define a function to classify the exercise type
      def classify_exercise(keypoints):
          # Placeholder logic for exercise classification
          # Replace with actual logic based on keypoint analysis
          if some_condition_based_on_keypoints:
              return "pushup"
          elif some_other_condition_based_on_keypoints:
              return "pullup"
          else:
              return "unknown"
      
      # Initialize the AIGym object
      gym_objects = {
          "pushup": solutions.AIGym(show=True, kpts=[6, 8, 10]),
          "pullup": solutions.AIGym(show=True, kpts=[6, 8, 10]),
          # Add other exercises as needed
      }
      
      frame_count = 0
      current_exercise = "unknown"
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              print("Video frame is empty or video processing has been successfully completed.")
              break
          frame_count += 1
          results = model.track(im0, verbose=False)  # Tracking recommended
      
          # Classify the exercise based on keypoints
          keypoints = results[0].keypoints
          exercise_type = classify_exercise(keypoints)
      
          if exercise_type in gym_objects:
              gym_object = gym_objects[exercise_type]
              im0 = gym_object(im0).plot_im  # AIGym runs its own pose tracking
          
          video_writer.write(im0)
      
      cv2.destroyAllWindows()
      video_writer.release()
      Next Steps
      1. Refine Exercise Classification: Develop a robust method to classify exercises based on keypoint data. This could involve machine learning models trained on labeled exercise data.
      2. Expand Exercise Types: Add more exercises to the gym_objects dictionary and their corresponding keypoint checks.
      3. Optimize Performance: Ensure the solution runs efficiently in real-time, especially if processing live video feeds.

      For more detailed guidance and advanced configurations, you can refer to our Workouts Monitoring Guide.

      Feel free to experiment with this approach and let us know how it works for you! If you encounter any issues or have further questions, don't hesitate to reach out.

    2. Glenn JocherUltralytics(已编辑)

      @duncanwaugh hello,

      Thank you for your insightful question! You're correct that the current setup of Ultralytics YOLOv8 for workout monitoring is designed to track specific exercises like pushups, pullups, and ab workouts individually. However, your idea of having a live video feed that can dynamically identify and count different exercises in sequence is fascinating and certainly feasible with some modifications.

      Dynamic Exercise Recognition

      To achieve dynamic exercise recognition, you would need to implement a mechanism that can classify the type of exercise being performed in real-time and then switch to the matching AIGym counter. Here's a high-level approach to how you might achieve this:

      1. Exercise Classification: Use a classification model to identify the type of exercise being performed. This model can be trained to recognize different exercises based on the input video frames.

      2. Counter Switching: Once the exercise type is identified, switch to the AIGym instance (keypoints kpts) for that exercise. This can be done dynamically within the video processing loop.

      Example Implementation

      Below is a simplified example to illustrate this concept. This example assumes you have a model for exercise classification; AIGym runs its own pose model.

      import cv2
      from ultralytics import YOLO, solutions
      
      # Load models
      classification_model = YOLO("exercise_classification_model.pt")
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
      
      gym_objects = {
          "pushup": solutions.AIGym(show=True, kpts=[6, 8, 10]),
          "pullup": solutions.AIGym(show=True, kpts=[6, 8, 10]),
          "squat": solutions.AIGym(show=True, kpts=[12, 14, 16])
      }
      
      current_exercise = None
      frame_count = 0
      
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              print("Video frame is empty or video processing has been successfully completed.")
              break
      
          frame_count += 1
      
          # Classify exercise type every few frames
          if frame_count % 30 == 0:  # Adjust frequency as needed
              classification_results = classification_model.predict(im0)
              current_exercise = classification_model.names[classification_results[0].probs.top1]  # class name of the top-1 prediction
      
          if current_exercise:
              gym_object = gym_objects[current_exercise]
              im0 = gym_object(im0).plot_im  # AIGym runs its own pose tracking
      
          cv2.imshow("Workout Monitoring", im0)
          if cv2.waitKey(1) & 0xFF == ord("q"):
              break
      
      cap.release()
      cv2.destroyAllWindows()
      Key Points:
      • Exercise Classification: The classification_model predicts the type of exercise.
      • Counter Switching: Based on the predicted exercise, the corresponding AIGym object is used.
      • Dynamic Processing: This setup allows for dynamic switching between different exercises during a workout session.

      This approach provides a flexible and scalable solution for monitoring multiple types of exercises in a single session. For more detailed guidance and advanced configurations, you can refer to our Workouts Monitoring Guide.

      Feel free to experiment with this setup and adjust it to better fit your specific use case. If you encounter any issues or have further questions, don't hesitate to reach out!

    3. Glenn JocherUltralytics(已编辑)

      @duncanwaugh hello,

      Thank you for your enthusiasm! 😊

      To address your query about dynamically identifying and counting different exercises within a single workout session, such as transitioning from pushups to pullups, you would need to implement a mechanism that can classify the type of exercise being performed in real-time and then switch to the matching AIGym counter.

      Dynamic Exercise Recognition

      Here's a high-level approach to achieve this:

      1. Exercise Classification: Use a classification model to identify the type of exercise being performed. This model can be trained to recognize different exercises based on the input video frames.
      2. Counter Switching: Once the exercise type is identified, switch to the AIGym instance (keypoints kpts) for that exercise. This can be done dynamically within the video processing loop.
      Example Implementation

      Below is a simplified example to illustrate this concept. This example assumes you have a model for exercise classification; AIGym runs its own pose model.

      import cv2
      from ultralytics import YOLO, solutions
      
      # Load models
      classification_model = YOLO("exercise_classification_model.pt")
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
      
      gym_objects = {
          "pushup": solutions.AIGym(show=True, kpts=[6, 8, 10]),
          "pullup": solutions.AIGym(show=True, kpts=[6, 8, 10]),
          "squat": solutions.AIGym(show=True, kpts=[12, 14, 16])
      }
      
      current_exercise = None
      frame_count = 0
      
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              print("Video frame is empty or video processing has been successfully completed.")
              break
      
          frame_count += 1
      
          # Classify exercise type every few frames
          if frame_count % 30 == 0:  # Adjust frequency as needed
              classification_results = classification_model.predict(im0)
              current_exercise = classification_model.names[classification_results[0].probs.top1]  # class name of the top-1 prediction
      
          if current_exercise:
              gym_object = gym_objects[current_exercise]
              im0 = gym_object(im0).plot_im  # AIGym runs its own pose tracking
      
          cv2.imshow("Workout Monitoring", im0)
          if cv2.waitKey(1) & 0xFF == ord("q"):
              break
      
      cap.release()
      cv2.destroyAllWindows()
      Key Points:
      • Exercise Classification: The classification_model predicts the type of exercise.
      • Counter Switching: Based on the predicted exercise, the corresponding AIGym object is used.
      • Dynamic Processing: This setup allows for dynamic switching between different exercises during a workout session.

      This approach provides a flexible and scalable solution for monitoring multiple types of exercises in a single session. For more detailed guidance and advanced configurations, you can refer to our Workouts Monitoring Guide.

      Feel free to experiment with this setup and adjust it to better fit your specific use case. If you encounter any issues or have further questions, don't hesitate to reach out!

      1
    1. Paula DerrengerUltralytics(已编辑)

      Hello,

      Yes, you can monitor workouts using the CLI with the workout solution:

      yolo solutions workout source=path/to/video/file.mp4 kpts="[6, 8, 10]"

      The kpts argument selects the three keypoints whose angle is counted ([6, 8, 10] is for pushups). For more detailed information, please refer to the documentation.

      Happy training! 💪