0% found this document useful (0 votes)
4 views5 pages

BMI

The document outlines a Python script that uses OpenCV and MediaPipe to estimate a person's Body Mass Index (BMI) from webcam video by detecting body landmarks. It includes functions for calculating BMI, estimating height and weight based on detected landmarks, and displaying the results in real-time. The script captures video from the webcam, processes each frame to detect pose landmarks, and calculates and displays the BMI on the screen.

Uploaded by

Karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

BMI

The document outlines a Python script that uses OpenCV and MediaPipe to estimate a person's Body Mass Index (BMI) from webcam video by detecting body landmarks. It includes functions for calculating BMI, estimating height and weight based on detected landmarks, and displaying the results in real-time. The script captures video from the webcam, processes each frame to detect pose landmarks, and calculates and displays the BMI on the screen.

Uploaded by

Karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

import cv2

import mediapipe as mp

import numpy as np

import math

# Initialize MediaPipe Pose Model

mp_pose = mp.solutions.pose

pose = mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5)

mp_drawing = mp.solutions.drawing_utils

# Function to calculate BMI

def calculate_bmi(weight, height):

if height == 0:

return 0

height_in_meters = height / 100 # Convert height to meters

bmi = weight / (height_in_meters ** 2)

return bmi

# Function to compute Euclidean distance between two points

def euclidean_distance(p1, p2):

return math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2 + (p2.z - p1.z) ** 2)

# Function to estimate height based on landmarks

def estimate_height(landmarks):

# Get coordinates of key points: Nose, Chin, Chest

nose = landmarks[mp_pose.PoseLandmark.NOSE]

chin = landmarks[mp_pose.PoseLandmark.CHIN]

chest = landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER] # Using shoulder as a rough reference

# Calculate distances (nose to chin and chin to chest)

nose_to_chin = euclidean_distance(nose, chin)

chin_to_chest = euclidean_distance(chin, chest)

# Estimate height using the sum of distances as a proportion of the full body height

estimated_height = (nose_to_chin + chin_to_chest) * 3 # Empirical scaling factor (adjust as necessary)

return estimated_height
# Function to estimate weight based on estimated height (heuristic model)

def estimate_weight(height):

# A very simple heuristic based on height (this can be improved with a more advanced model)

# Rough weight estimate using height in cm, e.g., height * a constant factor

weight = (height - 100) * 1.2 # Example: Weight increases with height (in kg)

return weight

# Video Capture

cap = cv2.VideoCapture(0) # 0 for webcam, or path to video file

while cap.isOpened():

ret, frame = cap.read()

if not ret:

break

# Flip the frame horizontally for better UX

frame = cv2.flip(frame, 1)

# Convert frame to RGB (MediaPipe requires RGB)

rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Process the frame and get pose landmarks

results = pose.process(rgb_frame)

# If landmarks are detected, proceed with BMI calculation

if results.pose_landmarks:

mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)

# Extract landmarks from the pose

landmarks = results.pose_landmarks.landmark

# Estimate height from landmarks

height = estimate_height(landmarks)

# Estimate weight based on height (heuristic)

weight = estimate_weight(height)

# Calculate BMI

bmi = calculate_bmi(weight, height)


# Display BMI on the frame

cv2.putText(frame, f'BMI: {bmi:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)

# Display the frame

cv2.imshow('Live BMI Detection', frame)

# Break loop on 'q' key press

if cv2.waitKey(1) & 0xFF == ord('q'):

break

cap.release()

cv2.destroyAllWindows()
1. Imports:

 cv2: OpenCV is used for video processing and displaying the webcam feed.

 mediapipe: MediaPipe is a framework for building multimodal applied ML pipelines. Here, it's used for
detecting body landmarks (pose detection).

 numpy: This library is used for numerical calculations, though it's not heavily used in the code.

 math: Used for basic mathematical operations, including the Euclidean distance calculation.

2. Initializing MediaPipe Pose Model:

 mp_pose.Pose: MediaPipe's pose detection model.

 pose: An instance of the Pose model with a minimum detection confidence of 0.5 and tracking confidence of
0.5. This defines the minimum thresholds for detecting and tracking the body landmarks.

 mp_drawing: This is used for drawing the detected landmarks on the frame.

3. Functions:

calculate_bmi(weight, height):

 This function takes weight (in kilograms) and height (in centimeters) as input and returns the Body Mass
Index (BMI) using the formula: BMI=weight(height in meters)2\text{BMI} = \frac{\text{weight}}{(\text{height
in meters})^2}BMI=(height in meters)2weight

 The height is first converted from centimeters to meters before performing the calculation.

euclidean_distance(p1, p2):

 This function computes the Euclidean distance between two 3D points (p1 and p2) using the formula:

distance=

 It's used to calculate the physical distances between body landmarks (e.g., from the nose to the chin or from
the chin to the chest).

estimate_height(landmarks):

 This function estimates the height of the person based on the distances between key body landmarks.

o It uses the Nose landmark and approximates the chin using the MOUTH_LEFT landmark (since
MediaPipe doesn’t provide a direct CHIN landmark).

o It uses the LEFT_SHOULDER as a rough reference for the chest.

o The function calculates the Euclidean distances from the Nose to Chin and Chin to Chest (shoulder).

o These distances are added together and multiplied by an empirical scaling factor (*3) to estimate the
total height in centimeters.
estimate_weight(height):

 This is a simple heuristic function to estimate the person's weight based on their height.

 It uses the formula:

 This is a rough estimation, assuming that the person's weight is proportional to their height (this could be
refined with a better model or dataset).

4. Main Code Execution (Webcam Feed):

 cv2.VideoCapture(0): This line opens the webcam for capturing video frames.

 while cap.isOpened(): Starts an infinite loop that continuously processes the video frames.

o The cap.read() function reads the current frame from the webcam.

o frame = cv2.flip(frame, 1): This line flips the frame horizontally for better user experience (so that
the user sees a mirror image of themselves).

o rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB): MediaPipe requires the frame to be in RGB


format, so the BGR (OpenCV format) frame is converted to RGB.

o results = pose.process(rgb_frame): The frame is processed by MediaPipe's pose model to detect


body landmarks.

 Landmarks Detection:

o If pose landmarks are detected in the frame (if results.pose_landmarks:), the detected landmarks
are drawn onto the frame using mp_drawing.draw_landmarks.

o The landmarks are then extracted using results.pose_landmarks.landmark.

 Height and Weight Estimation:

o The function estimate_height(landmarks) is called to calculate the height using the detected
landmarks.

o Then, estimate_weight(height) is called to estimate the weight based on the calculated height.

 BMI Calculation:

o The BMI is calculated using the calculate_bmi(weight, height) function.

o The calculated BMI value is displayed on the screen using cv2.putText().

5. Display Output:

 The webcam feed with the drawn landmarks and the calculated BMI value is displayed in a window called
Live BMI Detection.

 The cv2.waitKey(1) allows for a 1ms delay between frames, and the loop will break if the "q" key is pressed.

6. Cleanup:

 After exiting the loop, the webcam feed is released using cap.release(), and all OpenCV windows are closed
using cv2.destroyAllWindows().

You might also like