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

BM I Calorie Prediction

This document is a Python script that implements a GUI application using Tkinter for predicting calorie burn based on exercise duration and estimating age and BMI from facial features. It utilizes machine learning models, specifically XGBoost for calorie prediction and a CNN for age and BMI estimation, along with OpenCV for face detection. The application allows users to load datasets, train models, and make predictions based on images or webcam input.

Uploaded by

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

BM I Calorie Prediction

This document is a Python script that implements a GUI application using Tkinter for predicting calorie burn based on exercise duration and estimating age and BMI from facial features. It utilizes machine learning models, specifically XGBoost for calorie prediction and a CNN for age and BMI estimation, along with OpenCV for face detection. The application allows users to load datasets, train models, and make predictions based on images or webcam input.

Uploaded by

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

from tkinter import *

import tkinter
from tkinter import filedialog
import numpy as np
from tkinter.filedialog import askopenfilename
import pandas as pd
from tkinter import simpledialog
import numpy as np
import cv2
import os
from Model import get_model
from keras.models import load_model
from keras.models import model_from_json

from xgboost import XGBRegressor


from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

main = tkinter.Tk()
main.title("Calorie Burnt Prediction using XGBoost & Exercise Duration") #designing
main screen
main.geometry("800x700")

global filename, xgb_model


global image
global model
global faceCascade
scaler1 = MinMaxScaler(feature_range = (0, 1))
scaler2 = MinMaxScaler(feature_range = (0, 1))

with open('model/age_model.json', "r") as json_file:


loaded_model_json = json_file.read()
age_model = model_from_json(loaded_model_json)
json_file.close()
age_model.load_weights("model/age_weights.h5") #MNIST model will be loaded here
age_model._make_predict_function()

def loadModel():
global model
global faceCascade
textarea.delete('1.0', END)
cascPath = "model/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
model = get_model(ignore_age_weights=True)
model.load_weights('model/bmi_model_weights.h5')
textarea.insert(END,"BMI Prediction & Face Detection Models loaded\n")

def getAge(image):
img = cv2.resize(image, (80,80))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,80,80,3)
img = np.asarray(im2arr)
img = img.astype('float32')
img = img/255
preds = age_model.predict(img)
predict = np.argmax(preds)
return predict
def predictBMI():
food = ""
global model
global faceCascade
global filename
filename = filedialog.askopenfilename(initialdir="images")
textarea.delete('1.0', END)
frame = cv2.imread(filename)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1, minNeighbors=5,
minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE)
print("Found {0} faces!".format(len(faces)))
img = None
for (x, y, w, h) in faces:
img = frame[y:y + (h+10), x:x + (w+10)]
if img is not None:
age = getAge(img)
img = cv2.resize(img,(224,224))
temp = []
temp.append(img)
temp = np.asarray(temp)
prediction = model.predict(temp)
bmi = prediction[0][0]
bmi = bmi / 20
if bmi >= 18.5 and bmi < 25:
food = "Fuits & Vegetables\nWholegrains\nLean Protein Sources\nLow Fat
Diary Products\nNuts & Seeds\nWater"
elif bmi < 18.5:
food = "Nuts & Nut Butter\nAvocado\nWhole Grains\nDiary Products\nLean
Protein Sources\nDried Fruit"
elif bmi > 25:
food= "Fuits & Vegetables\nWholegrains\nLean Protein Sources\nLow Fat
Diary Products\nLegumes\nWater"
textarea.insert(END,"Recommended Foods Based on Predicted BMI\n\n"+food)
textarea.update_idletasks()
img = cv2.imread(filename)
img = cv2.resize(img, (800,400))
cv2.putText(img, 'Predicted BMI based on facial features is : '+str(bmi),
(10, 25), cv2.FONT_HERSHEY_SIMPLEX,0.7, (255, 0, 0), 2)
cv2.putText(img, 'Predicted Age : '+str(age), (10, 45),
cv2.FONT_HERSHEY_SIMPLEX,0.7, (255, 0, 0), 2)
cv2.imshow('Predicted BMI based on facial features is : '+str(bmi), img)
cv2.waitKey(0)
else:
textarea.insert(END,"Facial Features not detected in uploaded image\n")

def webcamPredict():
global model
global faceCascade
textarea.delete('1.0', END)
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
height, width, channels = frame.shape
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1, minNeighbors=5,
minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE)
img = None
for (x, y, w, h) in faces:
img = frame[y:y + (h+10), x:x + (w+10)]
if img is not None:
age = getAge(img)
img = cv2.resize(img,(224,224))
temp = []
temp.append(img)
temp = np.asarray(temp)
prediction = model.predict(temp)
bmi = prediction[0][0]
bmi = bmi / 20
textarea.delete('1.0', END)
if bmi >= 18.5 and bmi < 25:
food = "Fuits & Vegetables\nWholegrains\nLean Protein Sources\nLow
Fat Diary Products\nNuts & Seeds\nWater"
elif bmi < 18.5:
food = "Nuts & Nut Butter\nAvocado\nWhole Grains\nDiary Products\
nLean Protein Sources\nDried Fruit"
elif bmi > 25:
food= "Fuits & Vegetables\nWholegrains\nLean Protein Sources\nLow
Fat Diary Products\nLegumes\nWater"
textarea.insert(END,"Recommended Foods Based on Predicted BMI\n\
n"+food)
textarea.update_idletasks()
cv2.putText(frame, 'Predicted BMI based on facial features is :
'+str(bmi), (10, 25), cv2.FONT_HERSHEY_SIMPLEX,0.7, (255, 0, 0), 2)
cv2.putText(frame, 'Predicted Age : '+str(age), (10, 50),
cv2.FONT_HERSHEY_SIMPLEX,0.7, (255, 0, 0), 2)
cv2.imshow("Predicted Ouput", frame)
if cv2.waitKey(650) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

def prediction(algorithm, y_test, predict):


#calculating MSE error
mse_error = mean_squared_error(y_test,predict)
textarea.insert(END,"XGBoost Mean Square Error : "+str(mse_error)+"\n\n")
predict = predict.reshape(predict.shape[0],1)
predict = scaler2.inverse_transform(predict)
predict = predict.ravel()
labels = scaler2.inverse_transform(y_test)
labels = labels.ravel()
for i in range(len(labels)):
textarea.insert(END,"Observed Burnt Calorie : "+str(labels[i])+" Predicted
Burnt Calorie : "+str(predict[i])+"\n")
#plotting comparison graph between original values and predicted values
plt.plot(labels, color = 'red', label = 'Original Burnt Calorie')
plt.plot(predict, color = 'green', label = 'Predicted Burnt Calorie')
plt.title(algorithm+" Burnt Calorie Prediction Graph")
plt.xlabel('Number of Test Records')
plt.ylabel('Burnt Calorie Prediction')
plt.legend()
plt.show()

def trainCalorieModel():
global scaler1, scaler2, xgb_model
textarea.delete('1.0', END)
exercise = pd.read_csv("Dataset/exercise.csv", usecols=['Duration'], nrows =
2000)
exercise = exercise.values
calories = pd.read_csv("Dataset/calories.csv", usecols=['Calories'], nrows =
2000)
calories = calories.values
exercise = scaler1.fit_transform(exercise)
calories = scaler2.fit_transform(calories)
X_train, X_test, y_train, y_test = train_test_split(exercise, calories,
test_size=0.2, random_state=0)
xgb_model = XGBRegressor()
xgb_model.fit(X_train, y_train)
predict = xgb_model.predict(X_test)
prediction("XGBoost Regression Calorie Prediction", y_test, predict)

def predictCalorie():
global scaler1, scaler2, xgb_model
textarea.delete('1.0', END)
exercise = simpledialog.askinteger("Enter Duration of Exercise as Integer
Value", "Enter Duration of Exercise as Integer Value")
exercise = float(str(exercise))
temp = []
temp.append([exercise])
temp = np.asarray(temp)
print(temp.shape)
temp = scaler1.transform(temp)
predict = xgb_model.predict(temp)
predict = predict.reshape(predict.shape[0],1)
predict = scaler2.inverse_transform(predict)
predict = predict.ravel()
predict = predict[0]
textarea.insert(END,"Duration of Exercise : "+str(exercise)+"\n")
textarea.insert(END,"XGBoost Predicted Burnt Calories : "+str(predict))

font = ('times', 16, 'bold')


title = Label(main, text='Calorie Burnt Prediction using XGBoost & Exercise
Duration', justify=LEFT)
title.config(bg='lavender blush', fg='DarkOrchid1')
title.config(font=font)
title.config(height=3, width=120)
title.place(x=100,y=5)
title.pack()

font1 = ('times', 13, 'bold')


model = Button(main, text="Load dataset", command=loadModel)
model.place(x=200,y=100)
model.config(font=font1)

trainxgb = Button(main, text="Train XGBoost Regression", command=trainCalorieModel)


trainxgb.place(x=100,y=150)
trainxgb.config(font=font1)

predictButton = Button(main, text="Predict Burnt Calorie", command=predictCalorie)


predictButton.place(x=450,y=150)
predictButton.config(font=font1)

bmiimage = Button(main, text="Predict Age & BMI from Image", command=predictBMI)


bmiimage.place(x=200,y=200)
bmiimage.config(font=font1)

exitapp = Button(main, text="Predict Age & BMI from Webcam", command=webcamPredict)


exitapp.place(x=200,y=250)
exitapp.config(font=font1)

font1 = ('times', 12, 'bold')


textarea=Text(main,height=18,width=120)
scroll=Scrollbar(textarea)
textarea.configure(yscrollcommand=scroll.set)
textarea.place(x=10,y=300)
textarea.config(font=font1)

main.config(bg='blue')
main.mainloop()

You might also like