简单实现 Django 写人脸识别 restful 接口(从0开发,示例)
记录一下思路 代码直接用就行,我把线程和并发部分删掉了,更容易看清思路。
流程:通过urls.py文件正则匹配views.py文件,views.py文件里定义restful api 接口,再通过views.py文件调用算法程序。
Django_RESTful 官网地址: https://www.django-rest-framework.org/
Django API 官网地址:https://docs.djangoproject.com/en/2.1/intro/tutorial01/
开始安装库
pip install djangorestframework
pip install django==2.1
创建一个django工程:
1、创建新项目
django-admin startproject face
2、创建一个app
切换到该项目下面:
python manage.py startapp faceapp
3、将生成的py文件应用数据库
python manage.py migrate
4、测试服务 端口默认8000
python manage.py runserver 0:9000 (可以设置服务器和端口,0就是0.0.0.0 的缩写)
在face项目中这个就是根目录
在face里设置settings.py文件
ALLOWED_HOSTS = ["*"] # 这个是设置允许访问主机IP
INSTALLED_APPS = [ 'rest_framework',] # 将rest_framework添加到INSTALLED_APPS 中,否则会找不到
写urls.py 这里只要可以匹配到veiws即可
from django.contrib import admin from django.urls import include, path from rest_framework import routers from facedemo import views router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('face/', views.Face.as_view(), name="user"), #这里匹配视图views.py ]
更改views.py 习惯性的加上 # encoding: utf-8 把你主程序的接口加入到views路径中,如果传图片需要base64解码。
# encoding: utf-8 import binascii import json import re import base64 from rest_framework.response import Response from django.http import HttpResponse from rest_framework.views import APIView import numpy as np from PIL import Image from io import BytesIO from scipy import misc import img_return ai = img_return.process # 解码base64 def base64_to_image(base64_str): base64_str = str(base64_str) base64_str = re.sub('^data:image/.+;base64,', '', base64_str) byte_data = base64.b64decode(base64_str) image_data = BytesIO(byte_data) img = Image.open(image_data) return img # rest_framework class Face(APIView): @staticmethod def post(request): data = request.data img_b64_1 = data['img1'] img_b64_2 = data['img2'] img1 = misc.imread(img_b64_1, mode='RGB') img2 = misc.imread(img_b64_2, mode='RGB') img1 = Image.fromarray(np.uint8(img1)) img2 = Image.fromarray(np.uint8(img2)) user_id, feature = ai(data['id'], img1, img2) return HttpResponse(json.dumps({'feature': str(feature)}))
最后写你的主程序(这里只是个示例,前面的框架不用动,你只要改这里的代码就行)
# encoding: utf-8 from PIL import Image import numpy as np # post传入两张图片 返回一个json文件 def process(uid, image1, image2): uid, img1, img2 = uid, image1, image2 if uid and img1.size[0] and img2.size[0]: json = {'sim': 66} result = uid, json return result
代码是简化了的,主要为了理清流程。实际应用中,你可以在里面加入线程和并发。