一,安装opencv
pip install opencv_python # 换成国内源安装
二,django 接口
1,django项目创建应用:serviceApp
2,urls.py
from django.urls import path
from . import views
app_name = 'serviceApp'
urlpatterns = [
path('platform/', views.platform, name='platform'), # 人脸识别开放平台
path('facedetect/', views.facedetect, name='facedetect'), # 人脸检测api
path('facedetectDemo/', views.facedetectDemo, name='facedetectDemo'), # 人脸检测api
]
3,views.py
from django.shortcuts import render
from django.shortcuts import HttpResponse
from .models import Doc
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404
from django.http import StreamingHttpResponse
import base64
face_detector_path = "serviceApp\\haarcascade_frontalface_default.xml"
face_detector = cv2.CascadeClassifier(face_detector_path) # 生成人脸检测器
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
def platform(request):
submenu = 'platform'
return render(request, 'platForm.html', {
'active_menu': 'service',
'sub_menu': submenu,
})
return HttpResponse(html)
@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)
@csrf_exempt
def facedetectDemo(request):
result = {}
if request.method == "POST":
if request.FILES.get('image') is not None: #
img = read_image(stream=request.FILES["image"])
else:
result["#faceNum"] = -1
return JsonResponse(result)
if img.shape[2] == 3:
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 彩色图像转灰度图像
else:
imgGray = img
#进行人脸检测
values = face_detector.detectMultiScale(imgGray,
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]
# 将检测框显示在原图上
for (w, x, y, z) in values:
cv2.rectangle(img, (w, x), (y, z), (0, 255, 0), 2)
retval, buffer_img = cv2.imencode('.jpg', img) # 在内存中编码为jpg格式
img64 = base64.b64encode(buffer_img) # base64编码用于网络传输
img64 = str(img64, encoding='utf-8') # bytes转换为str类型
result["img64"] = img64 # json封装
return JsonResponse(result)
face_detector_path = "serviceApp\\haarcascade_frontalface_default.xml" 是opencv自带的训练好的人脸识别配置文件,在python安装目录下Lib\site-packages\cv2\data\ 下,复制到views.py同级目录方便使用。
4,templates/platForm.html
{% extends "base.html" %}
{% load static %}
{% block title %}
人脸识别开放平台
{% endblock %}
{% block content %}
<link href="{% static 'css/news.css' %}" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/codemirror.css' %}">
<script src="{% static 'js/codemirror.js' %}"></script>
<script src="{% static 'js/python.js' %}"></script>
<style type="text/css">
.CodeMirror {
border-top: 1px solid black;
border-bottom: 1px solid black;
}
</style>
<!-- 广告横幅 -->
<div class="container-fluid">
<div class="row">
<img class="img-responsive model-img" src="{% static 'img/service.jpg' %}">
</div>
</div>
<!-- 主体内容 -->
<div class="container">
<div class="row row-3">
<!-- 侧边导航栏 -->
<div class="col-md-3">
<div class="model-title">
服务支持
</div>
<div class="model-list">
<ul class="list-group">
<li class="list-group-item" id='download'>
<a href="{% url 'serviceApp:download' %}">资料下载</a>
</li>
<li class="list-group-item" id='platform'>
<a href="{% url 'serviceApp:platform' %}">人脸识别开放平台</a>
</li>
</ul>
</div>
</div>
<!-- 说明文字和图片 -->
<div class="col-md-9">
<div class="model-details-title">
人脸识别接口文档
</div>
<div class="model-details">
<h3>一. 体验产品</h3>
</br>
<!-- 按钮触发模态框 -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
人脸检测
</button>
<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
在线人脸检测
</h4>
</div>
<div class="modal-body">
<img id="photoIn" src="{% static 'img/sample.png' %}" class="img-responsive"
style="max-width:250px">
<input type="file" id="photo" name="photo" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭
</button>
<button type="button" id="compute" class="btn btn-primary">
开始检测
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<script>
$(function () {
$('#photo').on('change', function () {
var r = new FileReader();
f = document.getElementById('photo').files[0];
r.readAsDataURL(f);
r.onload = function (e) {
document.getElementById('photoIn').src = this.result;
};
});
});
</script>
<script>
$('#compute').click(function () {
formdata = new FormData();
var file = $("#photo")[0].files[0];
formdata.append("image", file);
$.ajax({
url: '/serviceApp/facedetectDemo/', // 调用Django服务器计算函数
type: 'POST', // 请求类型
data: formdata,
dataType: 'json', // 期望获得的响应类型为json
processData: false,
contentType: false,
success: ShowResult // 在请求成功之后调用该回调函数输出结果
})
})
</script>
<script>
function ShowResult(data) {
var v = data['img64'];
document.getElementById('photoIn').src = "data:image/jpeg;base64, " + v;
}
</script>
<h3>二. API接口说明</h3>
</br>
<h4><strong>基本信息:</strong></h4>
<p>
请求类型:HTTP/HTTPS。请求方式:POST
</p>
<p>
接口地址:http://myhengda.cn/serviceApp/facedetect/
</p>
</br>
<h4><strong>接口描述:</strong></h4>
<p>
人脸检测,此接口多用于调用人脸识别、人脸比对的接口之前,用于从图像数据中检测出人脸区域,并以
矩形框形式返回人脸检测结果。目前该接口仅供测试使用,调用该接口暂时不限制调用次数。
</p>
</br>
<h4><strong>本地调用示例:</strong></h4>
<div><textarea id="code" name="code">
import cv2, requests
# web地址(http://localhost:8000)+访问接口(facedetect)
url = "http://localhost:8000/serviceApp/facedetect/"
# 上传图像并检测
tracker = None
imgPath = "face.jpg" #图像路径
files = {
"image": ("filename2", open(imgPath, "rb"), "image/jpeg"),
}
req = requests.post(url, data=tracker, files=files).json()
print("获取信息: {}".format(req))
# 将检测结果框显示在图像上
img = cv2.imread(imgPath)
for (w, x, y, z) in req["faces"]:
cv2.rectangle(img, (w, x), (y, z), (0, 255, 0), 2)
cv2.imshow("face detection", img)
cv2.waitKey(0)
</textarea></div>
</br>
<h4><strong>调用结果:</strong></h4>
<img class="img-responsive" style="max-width:200px;" src="{% static 'img/facedetect.png' %}">
</div>
</div>
</div>
</div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {
name: "python",
version: 3,
singleLineStringErrors: false
},
lineNumbers: true,
indentUnit: 4,
tabMode: "shift",
matchBrackets: true
});
</script>
{% endblock %}
模板文件使用了codeMirror 插件, 地址:CodeMirror,需要把
<link rel="stylesheet" href="{% static 'css/codemirror.css' %}">
<script src="{% static 'js/codemirror.js' %}"></script>
这两个文件放到项目的静态文件夹 static/css/和static/js/ 目录下
5,页面效果
三,接口测试
1, tests.py
import cv2, requests
url = "http://localhost:8000/serviceApp/facedetect/" # web地址(http://localhost:8000)+访问接口(facedetect)
# 上传图像并检测
tracker = None
imgPath = "face.jpg" #图像路径
files = {
"image": ("filename2", open(imgPath, "rb"), "image/jpeg"),
}
req = requests.post(url, data=tracker, files=files).json()
print("获取信息: {}".format(req))
# 将检测结果框显示在图像上
img = cv2.imread(imgPath)
for (w, x, y, z) in req["faces"]:
cv2.rectangle(img, (w, x), (y, z), (0, 255, 0), 2)
cv2.imshow("face detection", img)
cv2.waitKey(0)
测试结果