在Django中快速进行简单的人脸识别

美好的一天!

我叫安德烈·索博列夫(Andrey Sobolev),今天我们将为Django创建一个简单的“小圆面包”,它将检查照片中人物的脸部(在很多情况下非常有用)。

为此,我们需要OpenCV和5分钟的空闲时间。走。

安装


首先,在docker容器中安装必要的库:

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/
* * *

并将依赖项添加到requirements.txt:

opencv-python
matplotlib
numpy

人脸检查功能detect_face


创建utils.py文件(例如,在主文件夹中,您可以具有任何其他文件夹),并在其中添加以下行:

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

集成到用户输入表单中


导入我们的功能:

from main.utils import detect_face 

并且在注册新用户时“检查面部”。

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"))

没有框架的例子


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)

就这样。

如您所见,一切都非常简单(当然,如果您需要简单检查)。

有用的链接


endingdatascience.com/face-detection-in-2-minutes-using-opencv-python-90f89d7c0f81
new-friend.org/ru/195/2800/12918/profile-registration(此解决方案的工作方式示例)。

All Articles