How To Create Fitness Tracker Using Python, Django, and OpenCV


Hi, I’m Asif Khan. Welcome to our Django blog! In the era of smart technology, home fitness trackers are gaining popularity for their ability to monitor and enhance workout routines. If you’re interested in building your own fitness tracker from scratch, this guide will walk you through creating a DIY home fitness tracker using Python, Django, and OpenCV.

Why Build a DIY Home Fitness Tracker?

Building a home fitness tracker has several benefits:

  • Personalization: Customize features according to your workout needs.
  • Cost-Effective: Save money compared to commercial fitness trackers.
  • Learning Experience: Gain hands-on experience with Python, Django, and computer vision.

Overview of the Project

This project involves:

  1. Setting Up Django: To create a web application for user interaction.
  2. Using OpenCV: For real-time video processing to track movements.
  3. Integrating Python: To handle backend logic and data processing.

Prerequisites

Before we start, make sure you have:

  • Python installed on your system.
  • Basic knowledge of Django, Python, and OpenCV.
  • Necessary libraries: Django, OpenCV, Pillow.

Step 1: Setting Up Your Django Project

  1. Create a New Django Project Open your terminal and run:
   django-admin startproject fitness_tracker
   cd fitness_tracker
  1. Create a New Django App
   python manage.py startapp tracker
  1. Update Settings Add 'tracker' to the INSTALLED_APPS list in fitness_tracker/settings.py:
   INSTALLED_APPS = [
       ...
       'tracker',
   ]
  1. Define Models In tracker/models.py, define a model to store workout data:
   from django.db import models

   class Workout(models.Model):
       timestamp = models.DateTimeField(auto_now_add=True)
       duration = models.PositiveIntegerField()  # Duration in seconds
       calories_burned = models.FloatField()

Run migrations to create the model:

   python manage.py makemigrations
   python manage.py migrate

Step 2: Setting Up OpenCV for Motion Tracking

  1. Install OpenCV Install OpenCV and other dependencies:
   pip install opencv-python-headless numpy
  1. Create a Motion Detection Script Create a file named motion_detection.py in the tracker directory:
   import cv2
   import numpy as np

   def detect_motion(frame1, frame2):
       diff = cv2.absdiff(frame1, frame2)
       gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
       blur = cv2.GaussianBlur(gray, (5, 5), 0)
       _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
       dilated = cv2.dilate(thresh, None, iterations=2)
       contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
       for contour in contours:
           (x, y, w, h) = cv2.boundingRect(contour)
           if cv2.contourArea(contour) > 500:
               return True
       return False

Step 3: Integrate Motion Detection with Django

  1. Create Views for Fitness Tracking In tracker/views.py, add the following code:
   from django.shortcuts import render
   from django.http import JsonResponse
   from .models import Workout
   from .motion_detection import detect_motion
   import cv2

   def track_workout(request):
       # Capture video from webcam
       cap = cv2.VideoCapture(0)
       workout_started = False
       duration = 0
       calorie_burned = 0

       while True:
           ret, frame1 = cap.read()
           ret, frame2 = cap.read()
           if detect_motion(frame1, frame2):
               if not workout_started:
                   workout_started = True
               duration += 1  # Increment duration (assuming 1-second intervals)
               # Calculate calories burned (dummy value here, replace with real formula)
               calorie_burned += 0.05
           else:
               if workout_started:
                   break

       cap.release()

       # Save workout data
       workout = Workout(duration=duration, calories_burned=calorie_burned)
       workout.save()

       return JsonResponse({'duration': duration, 'calories_burned': calorie_burned})
  1. Create a Template for Tracking Workouts In tracker/templates/tracker/track_workout.html, create a simple template:
   <!DOCTYPE html>
   <html>
   <head>
       <title>Fitness Tracker</title>
   </head>
   <body>
       <h1>Start Your Workout</h1>
       <button onclick="startWorkout()">Start Workout</button>
       <p id="result"></p>

       <script>
           function startWorkout() {
               fetch('/track-workout/')
                   .then(response => response.json())
                   .then(data => {
                       document.getElementById('result').innerText = 
                           `Duration: ${data.duration} seconds, Calories Burned: ${data.calories_burned}`;
                   });
           }
       </script>
   </body>
   </html>
  1. Configure URLs In tracker/urls.py, set up URL routing:
   from django.urls import path
   from . import views

   urlpatterns = [
       path('track-workout/', views.track_workout, name='track_workout'),
   ]

Include these URLs in your project’s urls.py:

   from django.contrib import admin
   from django.urls import path, include

   urlpatterns = [
       path('admin/', admin.site.urls),
       path('', include('tracker.urls')),
   ]

Step 4: Testing and Deployment

  1. Run Your Django Development Server Start the server with:
   python manage.py runserver

Visit http://127.0.0.1:8000/ to test the fitness tracker.

  1. Deploy Your Application Deploy your Django app using a platform like Heroku, AWS, or DigitalOcean to make it accessible online.

Conclusion

You’ve successfully created a DIY home fitness tracker using Python, Django, and OpenCV! This project showcases how you can integrate motion detection with web applications to build a personalized fitness tool.

Further Reading:

Get In Touch:

Feel free to customize and extend this fitness tracker according to your needs. Happy coding!


Leave a Comment

Your email address will not be published. Required fields are marked *


Shopping Basket
Scroll to Top