Track Bicep Curl Reps with Python AI

Track Bicep Curl Reps with Python AI

Table of Contents

  1. Introduction
  2. Setting Up the Python Script
  3. Creating the Camera Class
  4. Building the Graphical User Interface
  5. Implementing the Machine Learning Model
  6. Training and Predicting with the Model
  7. Adding Functionality to the GUI
  8. Finalizing the Script
  9. Conclusion

🎯Introduction

In this Tutorial, we will be building a Python script that uses machine learning to count the number of bicep curl reps performed using a dumbbell. The script will utilize a camera to capture the exercise movements and a machine learning model to analyze and count the reps. We will guide you through the process of setting up the script, developing the graphical user interface, implementing the machine learning model, and training and predicting with the model. By the end of this tutorial, you will have a fully functional Python script that can count your bicep curl reps using machine learning.

🛠️Setting Up the Python Script

To get started, you will need to have Python installed on your computer. Once you have Python installed, open the command Prompt or terminal and follow these steps:

  1. Install the required modules by typing the following commands:

    • pip install pillow
    • pip install opencv-python
    • pip install scikit-learn
  2. Split the program into four files:

    • app.py: Contains the graphical user interface (GUI) implementation.
    • main.py: A main file that combines all the components of the script.
    • camera.py: Contains the camera class for capturing the exercise movements.
    • model.py: Implements the machine learning model for counting the reps.
  3. Import the necessary modules in each file:

    • import tkinter as tk for the GUI.
    • import os and import cv2 for the camera class.
    • import numpy as np and from sklearn.svm import LinearSVC for the machine learning model.

🔍Creating the Camera Class

In the camera.py file, we will define the camera class for capturing the exercise movements. The camera class will have an initialization method for creating a camera object, a get_frame() method for retrieving the current frame from the camera, and a delete() method for releasing the camera resource when we are done.

Here is the code for the Camera class:

import cv2

class Camera:
    def __init__(self):
        self.camera = cv2.VideoCapture(0)  # Use camera index 0 for the primary camera

        if not self.camera.isOpened():
            raise ValueError("Camera not found.")

    def get_frame(self):
        ret, frame = self.camera.read()
        if ret:
            return frame
        else:
            return None

    def delete(self):
        if self.camera.isOpened():
            self.camera.release()

💻Building the Graphical User Interface

In the app.py file, we will build the graphical user interface (GUI) for our script using the Tkinter library. The GUI will consist of various buttons and a canvas for displaying the camera feed.

Here is the code for the App class that creates the GUI:

import tkinter as tk
import os
from PIL import Image, ImageTk
import cv2
from camera import Camera
from model import Model

class App:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("Bicep Curl Counter")

        # Initialize counters and flags
        self.extended = False
        self.contracted = False
        self.last_prediction = 0
        self.counting_enabled = False
        self.rep_counter = 0

        # Create camera object
        self.camera = Camera()

        # Create GUI elements
        self.canvas = tk.Canvas(self.window, width=self.camera.width, height=self.camera.height)
        self.canvas.pack(anchor=tk.NW, expand=True)

        self.button_toggle_count = tk.Button(self.window, text="Toggle Counting", command=self.counting_toggle)
        self.button_toggle_count.pack(anchor=tk.NW, expand=True)

        self.button_class1 = tk.Button(self.window, text="Add Example (Extended)", command=lambda: self.save_for_class(1))
        self.button_class1.pack(anchor=tk.NW, expand=True)

        self.button_class2 = tk.Button(self.window, text="Add Example (Contracted)", command=lambda: self.save_for_class(2))
        self.button_class2.pack(anchor=tk.NW, expand=True)

        self.button_train = tk.Button(self.window, text="Train Model", command=self.train_model)
        self.button_train.pack(anchor=tk.NW, expand=True)

        self.button_reset = tk.Button(self.window, text="Reset", command=self.reset)
        self.button_reset.pack(anchor=tk.NW, expand=True)

        self.counter_label = tk.Label(self.window, font=("Arial", 24), text=f"Reps: {self.rep_counter}")
        self.counter_label.pack(anchor=tk.NW, expand=True)

    def counting_toggle(self):
        self.counting_enabled = not self.counting_enabled

    def save_for_class(self, class_num):
        frame = self.camera.get_frame()
        if not os.path.exists(str(class_num)):
            os.makedirs(str(class_num))
        cv2.imwrite(f"{class_num}/frame.jpg", frame)

    def train_model(self):
        self.model = Model()
        self.model.train(self.counter_list)

    def reset(self):
        self.rep_counter = 0
        self.counter_label.config(text=f"Reps: {self.rep_counter}")

    def update(self):
        frame = self.camera.get_frame()
        if frame is not None:
            self.photo = ImageTk.PhotoImage(image=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
            self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)

        if self.counting_enabled:
            self.predict(frame)

            if self.extended and self.contracted:
                self.extended = False
                self.contracted = False
                self.rep_counter += 1
                self.counter_label.config(text=f"Reps: {self.rep_counter}")

        self.window.after(10, self.update)

app = App()

🤖Implementing the Machine Learning Model

In the model.py file, we will define the Model class, which implements the machine learning model for counting the bicep curl reps. We will use the linear support vector classifier from the scikit-learn library.

Here is the code for the Model class:

import cv2
import numpy as np
from sklearn.svm import LinearSVC

class Model:
    def __init__(self):
        self.model = LinearSVC()

    def train(self, counters):
        image_list = np.empty((0, 16950))
        class_list = np.empty((0))

        for i in range(1, counters[0] + 1):
            image = cv2.imread(f"1/frame{i}.jpg", cv2.IMREAD_GRAYSCALE)
            image = image.reshape(1, -1)
            image_list = np.append(image_list, image, axis=0)
            class_list = np.append(class_list, 1)

        for i in range(1, counters[1] + 1):
            image = cv2.imread(f"2/frame{i}.jpg", cv2.IMREAD_GRAYSCALE)
            image = image.reshape(1, -1)
            image_list = np.append(image_list, image, axis=0)
            class_list = np.append(class_list, 2)

        image_list = image_list.reshape((-1, counters[0] + counters[1]))

        self.model.fit(image_list, class_list)
        print("Model successfully trained.")

    def predict(self, frame):
        cv2.imwrite("frame.jpg", frame)
        image = cv2.imread("frame.jpg", cv2.IMREAD_GRAYSCALE)
        image = image.reshape(1, -1)
        prediction = self.model.predict(image)
        return prediction[0]

🏋️Training and Predicting with the Model

To train the model and make predictions, we will use the buttons and the camera feed from the GUI. The Add Example buttons will save images of the extended and contracted arms for training the model. The Train Model button will train the model on the collected training examples. The Toggle Counting button will start or stop the counting based on the predicted reps.

🔧Adding Functionality to the GUI

The Update function in the GUI will continuously capture frames from the camera and update the canvas display. It will also call the predict function to make predictions based on the frames received. If there is a change in the prediction, the extended and contracted flags will be set accordingly. When both flags are set, the reps counter will be incremented.

✅Finalizing the Script

To finalize the script, we need to create a main.py file to combine all the components together. In the main function, we will create an instance of the App class and run the main loop.

Here is the code for the main.py file:

from app import App

def main():
    app = App()
    app.window.mainloop()

if __name__ == "__main__":
    main()

🎉Conclusion

Congratulations! You have successfully built a Python script that uses machine learning to count the number of bicep curl reps using a dumbbell. The script includes a graphical user interface for user interaction, a camera class for capturing movements, and a machine learning model for rep counting. You can now use the script during your exercise routine to automatically count your bicep curls. Keep practicing and enjoy your workouts!

Resources:

FAQ:

Q: Can I use this script with multiple cameras? A: Yes, you can specify the camera index in the Camera class initialization. Use index 0 for the primary camera and try different indexes for multiple cameras to find the one you want to use.

Q: How accurate is the rep counting? A: The accuracy of the rep counting depends on various factors, including the quality of the camera, lighting conditions, and the training examples provided. It is recommended to capture consistent and clear images for accurate counting.

Q: Can I use this script for other exercises? A: This script is specifically designed for counting bicep curl reps. However, you can modify and extend the script to count reps for other exercises by providing appropriate training examples and updating the machine learning model accordingly.

Q: How can I improve the accuracy of the rep counting? A: To improve the accuracy, ensure consistent lighting conditions and capture training examples from different angles and variations of the exercise. Additionally, you can experiment with different machine learning models and parameters to find the best configuration for your specific use case.

Q: Can I use a different machine learning model instead of LinearSVC? A: Yes, you can experiment with different machine learning models available in scikit-learn to find the one that works best for your specific use case. Just make sure to update the model.py file accordingly. Be aware that more complex models may require additional computational resources.

Most people like

Find AI tools in Toolify

Join TOOLIFY to find the ai tools

Get started

Sign Up
App rating
4.9
AI Tools
20k+
Trusted Users
5000+
No complicated
No difficulty
Free forever
Browse More Content