Skip to content

Commit 241759d

Browse files
Merge branch 'abhisheks008:main' into main
2 parents d40c669 + dd84d26 commit 241759d

File tree

226 files changed

+88410
-4370
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

226 files changed

+88410
-4370
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
## Web Application for Age and Sex Prediction using Flask
2+
3+
### Goal 🎯
4+
The main goal is to develop a user-friendly web application that predicts age and gender from human images using deep learning models. This application will allow users to upload images and receive predictions.
5+
6+
### Model used for the Web App 🧮
7+
The backend of this web application utilizes Convolutional Neural Networks (CNNs) for age and gender prediction. It has been trained on [UTKFace Dataset](https://www.kaggle.com/datasets/jangedoo/utkface-new) dataset that contains over 20000 facial images for 30 epochs.
8+
9+
Key Details:
10+
* **Model Architecture:** It utilizes Convolutional Neural Network.
11+
* **Data Processing**: Input images are converted to Grayscale images, resized to 128x128 pixels, and normalized.
12+
* **Frameworks and Libraries**: The model is implemented using TensorFlow and Keras for deep learning tasks, and OpenCV for image processing.
13+
* **Model Training**: The model uses categorical cross-entropy loss and Mean Average Error for gender and age respectively and the Adam optimizer. And sigmoid and ReLU activation functions are used for gender and age respectively. It has been trained for 30 epochs.
14+
* **Deployment**: The model is deployed using Flask, providing a web application to interact with the deep learning model efficiently.
15+
This setup enhances user interface allowing real-time predictions.
16+
17+
18+
### Video Demonstration 🎥
19+
20+
[!()](https://github.com/theiturhs/DL-Simplified/assets/96874023/03bdb810-4b52-4606-9bc4-1384fcecb595)
21+
22+
### Signature ✒️
23+
**Shruti Shrivastava**
24+
25+
[![LinkedIn](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/shrutikshrivastava/)
26+
[![Gmail](https://img.shields.io/badge/Gmail-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:[email protected])
27+
[![Carrd](https://img.shields.io/badge/carrd-000000?style=for-the-badge&logo=carrd&logoColor=white)](https://theiturhs.carrd.co/)
28+
[![Kaggle](https://img.shields.io/badge/kaggle-0077B5?style=for-the-badge&logo=kaggle&logoColor=white)](https://www.kaggle.com/theiturhs)
29+
[![GitHub](https://img.shields.io/badge/github-000000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/theiturhs)

Age and Sex Prediction/Web App/app.py

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
from flask import Flask, render_template, request, redirect, url_for, session
2+
import os
3+
import numpy as np
4+
import cv2
5+
import tensorflow as tf
6+
import sys
7+
8+
sys.stdout.reconfigure(encoding='utf-8')
9+
10+
app = Flask(__name__)
11+
app.config['JSON_AS_ASCII'] = False
12+
app.secret_key = os.urandom(24)
13+
14+
UPLOAD_FOLDER = 'static'
15+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
16+
17+
# loading the model
18+
# model is saved in static folder
19+
model = tf.keras.models.load_model('static/age_and_gender_prediction_model.h5')
20+
21+
# gender mapping
22+
# if gender prediction = 0, the predition is MALE
23+
# else FEMAL
24+
gender_dict = {0: 'Male', 1: 'Female'}
25+
26+
# Function to extract face from uploaded image
27+
# The dataset on which model was trained contained only face images
28+
# This function finds the face area using
29+
# a haar cascade designed by OpenCV to detect the frontal face
30+
def extract_face():
31+
32+
img = cv2.imread('static/uploaded_img.jpg') # reading uploaded image
33+
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # converted to grayscale
34+
35+
# OpenCV's CascadeClassifier to load a pre-trained Haar cascade for detecting frontal faces
36+
haar_cascade = cv2.CascadeClassifier('static/haarcascade_frontalface_default.xml')
37+
faces_rect = haar_cascade.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=9)
38+
extracted_faces = []
39+
40+
if len(faces_rect) == 0:
41+
cv2.imwrite('static/extracted.jpg', img) # if no coordinates are detected, its only face image
42+
else:
43+
extracted_faces = []
44+
for (x, y, w, h) in faces_rect:
45+
face = img[y:y+h, x:x+w]
46+
extracted_faces.append(face)
47+
concatenated_faces = cv2.hconcat(extracted_faces)
48+
cv2.imwrite('static/extracted.jpg', concatenated_faces) # face extracted image - saved as extracted.jpg
49+
50+
if len(faces_rect) != 0:
51+
for (x, y, w, h) in faces_rect:
52+
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), thickness=2)
53+
cv2.imwrite('static/uploaded_img.jpg', img) # original uploaded image where face is marked
54+
55+
# Function to extract features from the image
56+
# This is the pre-process technique
57+
# which was applied on original dataset before training
58+
def extract_features(images):
59+
img = cv2.imread(images, cv2.IMREAD_GRAYSCALE) # Read image in grayscale
60+
img = cv2.resize(img, (128, 128)) # Resize image
61+
img = np.array(img) # Convert image to numpy array
62+
features = img.reshape(1, 128, 128, 1) # Reshape to match input shape
63+
return features
64+
65+
# Function to predict gender and age
66+
def predict_result():
67+
X = extract_features('static/extracted.jpg')
68+
X = X/255.0
69+
pred = model.predict(X.reshape(1, 128, 128, 1))
70+
pred_gender = gender_dict[round(pred[0][0][0])]
71+
pred_age = round(pred[1][0][0])
72+
return pred_gender, pred_age
73+
74+
@app.route('/prediction')
75+
def prediction():
76+
image_filename = 'static/extracted.jpg'
77+
gender, age = predict_result()
78+
if image_filename:
79+
return render_template('prediction_page.html', age=age, gender=gender)
80+
else:
81+
return render_template('not_found.html') # Redirect to the 'not_found' page
82+
83+
@app.route('/', methods=['GET', 'POST'])
84+
def home():
85+
if request.method == 'POST' and 'face_image' in request.files:
86+
face_image = request.files['face_image']
87+
if face_image.filename != '':
88+
image_filename = 'uploaded_img.jpg'
89+
image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_filename)
90+
face_image.save(image_path)
91+
session['image_filename'] = image_filename
92+
extract_face()
93+
return redirect(url_for('prediction')) # Redirect to the 'prediction' route
94+
return render_template('index.html')
95+
96+
@app.route('/not_found')
97+
def not_found():
98+
return render_template('not_found.html')
99+
100+
if __name__ == "__main__":
101+
app.run(debug=True, port=8000)
1.16 MB
Binary file not shown.
Binary file not shown.
Loading

0 commit comments

Comments
 (0)