Simple face recognition on the fly in Django

Good day!

My name is Andrey Sobolev and today we will create a simple “bun” for Django, which will check that the person’s face in the photo (which is useful in a bunch of situations).

To do this, we need OpenCV and 5 minutes of free time. Go.

Installation


First, install the necessary libraries in the docker container:

FROM python:3.8.3-buster

RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y \
    gcc && apt-get install -y \  
    libcurl4-gnutls-dev libexpat1-dev gettext libz-dev libssl-dev libjpeg-dev libfreetype6-dev python-dev libpq-dev python-dev libxml2-dev libxslt-dev postgresql-client git && \
    apt-get install -y libxrender1 libxext-dev fontconfig && \
    pip3 install -U pip setuptools 

COPY ./requirements.txt /home/
* * *

And add the dependencies to requirements.txt:

opencv-python
matplotlib
numpy

Face check function detect_face


Create the utils.py file (for example, in the main folder, you can have any other folder) and add the following lines there:

import cv2 as cv
import numpy as np

def detect_face(in_memory_photo):
    face_cascade = cv.CascadeClassifier(cv.__path__[0] + "/data/haarcascade_frontalface_default.xml")
    in_memory_photo = in_memory_photo.read()
    nparr = np.fromstring(in_memory_photo, np.uint8)
    img = cv.imdecode(nparr, 4)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    if len(faces) > 0:
        return True
    else:
        return False

Integration into user input form


Import our function:

from main.utils import detect_face 

And “check the face” when registering a new user.

if request.method == "POST":
    form = RegistrationForm(request.POST, request.FILES)

    if form.is_valid():

        try:
            in_memory_uploaded_file = request.FILES["photo"]
        except:
            in_memory_uploaded_file = None

        if not in_memory_uploaded_file or not detect_face(in_memory_uploaded_file):
            messages.add_message(request, messages.WARNING, _("You can only upload a face photo. Please try to uploading a different photo."))
            return HttpResponseRedirect(reverse("main:profile_registration"))

An example without a framework


import os
import cv2 as cv
import numpy as np

def detect_face(in_memory_photo):
    face_cascade = cv.CascadeClassifier(cv.__path__[0] + "/data/haarcascade_frontalface_default.xml")
    in_memory_photo = in_memory_photo.read()
    nparr = np.fromstring(in_memory_photo, np.uint8)
    img = cv.imdecode(nparr, 4)
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    if len(faces) > 0:
        return True
    else:
        return False

with open(os.path.dirname(os.path.abspath(__file__)) + '/photo.jpg', 'rb') as in_memory_photo: 
    is_it_face = detect_face(in_memory_photo)
    print(is_it_face)

That's all.

As you can see, everything is quite simple (if you need a simple check of course).

useful links


towardsdatascience.com/face-detection-in-2-minutes-using-opencv-python-90f89d7c0f81
new-friend.org/ru/195/2800/12918/profile-registration (an example of how this solution works).

All Articles