Python Web开发:人脸识别后台搭建

来自CloudWiki
跳转至: 导航搜索

背景

以人脸检测为例,以Web形式提供服务,用户通过特定的API上传需要检测的照片,然后由WEB服务器将结果返回给用户

实训步骤

安装库

pip install numpy

pip install opencv_python

C:\Users\maxin\AppData\Local\Programs\Python\Python37\Lib\site-packages\cv2\data 中找到

haarcascade_frontalface_default.xml

并复制到serviceApp目录下。

编辑视图函数

import numpy as np  # 矩阵运算
import urllib  # url解析
import json  # json字符串使用
import cv2  # opencv包
import os  # 执行操作系统命令
from django.views.decorators.csrf import csrf_exempt  # 跨站点验证
from django.http import JsonResponse  # json字符串响应


face_detector_path = "serviceApp\\haarcascade_frontalface_default.xml"
face_detector = cv2.CascadeClassifier(face_detector_path)  # 生成人脸检测器


@csrf_exempt  # 用于规避跨站点请求攻击
def facedetect(request):
    result = {}

    if request.method == "POST":  # 规定客户端使用POST上传图片
        if request.FILES.get("image", None) is not None:  # 读取图像
            img = read_image(stream=request.FILES["image"])
        else:
            result.update({
                "#faceNum": -1,
            })
            return JsonResponse(result)

        if img.shape[2] == 3:
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 彩色图像转灰度图像

        #进行人脸检测
        values = face_detector.detectMultiScale(img,
                                                scaleFactor=1.1,
                                                minNeighbors=5,
                                                minSize=(30, 30),
                                                flags=cv2.CASCADE_SCALE_IMAGE)

        # 将检测得到的人脸检测关键点坐标封装
        values = [(int(a), int(b), int(a + c), int(b + d))
                  for (a, b, c, d) in values]
        result.update({
            "#faceNum": len(values),
            "faces": values,
        })
    return JsonResponse(result)

其中,read_image如下:

def read_image(stream=None):
    if stream is not None:
        data_temp = stream.read()
    img = np.asarray(bytearray(data_temp), dtype="uint8")
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    return img

url路由设置

serviceApp/urls.py:

from django.urls import path
from . import views

app_name = 'serviceApp'

urlpatterns = [
    path('download/', views.download, name='download'),  # 资料下载
    path('platform/', views.platform, name='platform'),  # 人脸识别开放平台
    path('getDoc/<int:id>/',views.getDoc,name='getDoc'),
    path('facedetect/',views.facedetect,name='facedetect'),#人脸检测API
]

保存修改运行项目。

验证

重启服务

浏览器输入:

http://127.0.0.1:8000/serviceApp/facedetect/