良い一日!私の名前は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)
それで全部です。ご覧のとおり、すべてが非常に単純です(もちろん、単純なチェックが必要な場合)。役立つリンク
向けてdatascience.com/face-detection-in-2-minutes-using-opencv-python-90f89d7c0f81new-friend.org/ru/195/2800/12918/profile-registration(このソリューションの仕組みの例)。