How I Created a Face-Detection App Using the Flask Framework : Jonathan Okah

How I Created a Face-Detection App Using the Flask Framework
by: Jonathan Okah
blow post content copied from  Be on the Right Side of Change
click here to view original post


5/5 - (1 vote)

Advancement in technology has witnessed the application of artificial intelligence to detect and recognize human faces. 👩👩‍🦲👨‍🦰 This is accomplished using OpenCV, a Python library for computer vision and image processing.

In the previous tutorials, we use OpenCV to process images and turn them into pencil drawings and cartoons. We will learn how to use the same library to detect human faces on images and render them on a Flask web application.

For our application to be able to detect a human face, it needs to be trained on large amounts of data that contain a sufficient representation of people from different backgrounds. This requires long hours of model training, and we don’t have all day for such a time-consuming task.

Thanks to the OpenCV library that comes with its trained models for face detection. All that we need to do is to use the algorithm to detect faces in our applications.

The Haar-Cascade Algorithm

The Haar-Cascade algorithm is a machine-learning model trained to detect objects in images. It can run in real-time. Haar-Cascade are nothing but XML files used in OpenCV to detect specified objects. It can detect various objects like buildings, eyes, noses, fruits, cars, mouths and bikes.

Depending on the object you want to detect, you first have to load the pre-trained XML files, if, of course, it’s available. To learn more about Haar-Cascades, check this article on Medium.

Using OpenCV for face detection

Let’s see how to use OpenCV for face detection. I will be using a particular picture for this demonstration. Feel free to use any picture of your choice. Create and move into a new folder for this project. Install opencv-python if you haven’t done so.

pip install opencv-python

Import the library and define the path to the image.

import cv2 as cv

image = 'Jonaben.jpg'

Make sure you have this image in your current folder. Let’s read the image using the imread() function.

img = cv.imread(image)

The image is returned as a NumPy array. Let’s see the shape of the image.

img.shape
(2560, 1920, 3)

The image is a three-dimensional array representing the height width and channels respectively. The three channels represent blue, green and red (BGR) colors as used in OpenCV.

Let’s convert the image to grayscale before performing face detection on it.

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

If you check the shape again, you will notice that it is now a 2-dimensional image as the color channel has been removed. Let’s now load call the Haar-Cascade algorithm.

face_classifier = cv.CascadeClassifier(
    cv.data.haarcascades + "haarcascade_frontalface_default.xml"
)

The haarcascade_frontalface_default.xml is a classifier for face detection. For other object detection classifiers, check this repository. We will now perform face detection using the classifier.

face = face_classifier.detectMultiScale(
    gray, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40)
)

The detectMultiscale() method will be used to identify faces of different sizes. The scaleFactor reduces the grayscale to 10% of the original sizes to accommodate faces of different scales. The minNeighbors parameter defines the number of neighbors each rectangle should have.

A higher value will give high quality but few detections. By specifying 5, we try to strike a balance between quality and quantity. The minSize is the minimum size a face should have. Any face less than that is completely ignored.

Now that the face is detected, let’s draw a rectangle over the detected face.

for (x, y, w, h) in face:
    cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)

The face is represented as a tuple consisting of x and y coordinates, width and height. We perform a for loop which iterates over the face and uses the rectangle() function to draw a green rectangle over the face using the coordinates and dimensions of the face. The value (0, 255, 0) is the green color and 4 is the thickness in pixels.

To display the image, we first have to turn it into RGB color format. Then, we use the matplotlib library to display the image

rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.figure(figsize=(20,10))
plt.imshow(rgb_img)
plt.axis('off')

Integrating Face Detection in Flask Application

We will create a Flask application to display the image faces detected by OpenCV. It will be similar to the sketch-making Flask application we created previously but with a few modifications. Therefore, you are required to go through that tutorial to understand how we created the application.

This is because I don’t want to repeat myself here to avoid bloating this article.  I will only show you what to do on the command line.

In your current folder, create two files: a folder (app by name) and a run.py file. Move inside the app folder.

mkdir app && touch run.py
cd app

Inside the app folder, create a file, capture.py (for Linux users, use nano capture.py on the command line) and write the following in it:

import cv2 as cv

def image_capture(img):
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_classifier = cv.CascadeClassifier(
        cv.data.haarcascades + "haarcascade_frontalface_default.xml"
)
    face = face_classifier.detectMultiScale(
       gray, scaleFactor=1.1, minNeighbors=5, minSize=(40,40)
    )
    for (x, y, w, h) in face:
        cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)

    rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    return rgb_img

This is exactly what we just did. It’s now wrapped in a function. Next, create an __init__.py and write the following:

from flask import Flask
from secrets import token_hex


UPLOAD_FOLDER = 'app/static/uploads'
SECRET_KEY = token_hex(16)


app = Flask(__name__)

app.config['SEND_FILE_MAXIMUM_AGE_DEFAULT'] = 0
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = SECRET_KEY


from app import main

Go through that article to understand what these configurations mean. Now, create a file.py file, and write the following:

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.')[1] in ALLOWED_EXTENSIONS

Next, the main.py file. Create it inside the app folder. Then, write these:

import cv2
import os
from werkzeug.utils import secure_filename
from flask import request, render_template
from app import app
from app.file import allowed_file
from app.capture import image_capture



UPLOAD_FOLDER = 'app/static/uploads'
CAPTURE_FOLDER = 'app/static/capture'


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/capture', methods=['GET', 'POST'])
def sketch():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename =secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        img = cv2.imread(UPLOAD_FOLDER+'/'+filename)
        capture_img = image_capture(img)
        capture_img_name = filename.split('.')[0]+'_capture.jpg'
        save = cv2.imwrite(CAPTURE_FOLDER+'/'+capture_img_name, capture_img)
        return render_template('home.html', org_img_name=filename, capture_img_name=capture_img_name)
    return render_template('home.html')

I made some modifications to that project article to correspond with what we are learning in this tutorial. The image, when uploaded, will go to a static folder as static file. Therefore, create the folder and inside the static folder, create two more folders.

mkdir -p static/uploads static/capture static/css

We also create a css folder for CSS files. So, once the uploaded file is received, it will be stored in the uploads folder. Then, we use OpenCV to read it and call the image_capture() for face detection.

The result is now stored in the capture folder and displayed in the Flask application.

On the terminal, create a home.html file. It will be inside the templates folder.

nano templates/home.html

Write the following in it:

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="static/css/styles.css">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Face Detection</title>
</head>

<body style="background:pink">

    <div class='regform mt-3'>
        <h1 style="text-align:center;">Flask Face Detection App</h1>
    </div>

    <form action='/capture' class='main-form' method="POST" enctype="multipart/form-data">

        <div class='text-center'>
            <input type="file" id="file" name='file' style="margin-top:10px;margin-bottom:10px;">
            <button type='submit' class='btn btn-outline-success'> Capture
            </button>
        </div>

    </form>

    

</body>
</html>

In your css folder, create a styles.css file:

body {
     font-family: sans-serif;
     margin-top: 40px;
}

   .regform {
     width: 800px;
     margin: auto;
     color: black;
     padding: 10px, 0px, 10px, 0px;
     text-align: center;
     border-radius: 15px, 15px, 0px, 0px;
}


   .main-form {
     width: 800px;
     margin: auto;
     padding-left: 50px;
     padding-right: 50px;
     color: #ffffff;
}

   img {
     max-height: 400px;
     max-width: 500px;
     height: auto;
     width: auto;
}

Finally, in your run.py file, write this:

from app import app


if __name__ == '__main__':
    app.run()

To start the local server, move into your project folder and type flask run in the terminal.

Conclusion

In this project, we have learned how to create a face-detection app using OpenCV and the Flask framework. Use this knowledge to improve your Python skills. Check my GitHub page for the source code.

We can take this app further perhaps, to add real-time face detection. Furthermore, we can create a face recognition app and render it on a Flask application. I may give attention to that in future project tutorials.

Thanks for staying with me throughout this tutorial. Enjoy your day!


June 18, 2023 at 06:14PM
Click here for more details...

=============================
The original post is available in Be on the Right Side of Change by Jonathan Okah
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce