參加一個比賽,指定用虹軟的人臉識別功能,奈何虹軟人臉識別要本身建人臉庫,否則就只能離線用,總不能裝個樣子,簡單看了下虹軟Demo,下面決定用這種簡單方法實如今線人臉識別:java
Android端(虹軟Demo)取出人臉信息和姓名,人臉信息寫入.data文件,存入手機本地------>取出文件上傳至Python Djano後臺,後臺把文件保
存在工程下並把路徑存入數據庫------>Android端訪問後臺接口,遍歷全部數據庫中文件路徑而後做爲參數再次訪問後臺,獲得全部人臉信息
文件和姓名,使用識別功能時,就能夠開始和全部人臉信息比對,獲得效果
Django 後臺代碼:數據庫
在工程下新建一個文件夾uploads,用來存放人臉數據.data文件django
爲簡單實現,在setting.py中註釋json
#'django.middleware.csrf.CsrfViewMiddleware',
否則post請求被攔截,認真作工程不建議這樣作
app.urls:網絡
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^posts',views.posttest), url(r'^getallface',views.getface), url(r'^filedown',views.file_download), ] views.py #coding:utf-8 import json from imp import reload import sys import os from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse from django.shortcuts import render, render_to_response from django.template import RequestContext from faceproject.settings import BASE_DIR, MEDIA_ROOT reload(sys) from faceapp.models import face, Faceinfos, FaceinfoForm def getface(request): if request.method=='GET': WbAgreementModel = Faceinfos.objects.all() cflist = [] cfdata = {} cfdata["coding"] = 1 cfdata['message'] = 'success' for wam in WbAgreementModel: wlist = {} wlist['name'] = wam.username wlist['faceinfo']=wam.fileinfo cflist.append(wlist) cfdata['data'] = cflist return HttpResponse(json.dumps(cfdata, ensure_ascii=False), content_type="application/json") def posttest(request): if request.method=='POST': files=request.FILES['fileinfo'] if not files: return HttpResponse("no files for upload!") Faceinfos( username=request.POST['username'], fileinfo=MEDIA_ROOT+'/'+files.name ).save() f = open(os.path.join('uploads', files.name), 'wb') for line in files.chunks(): f.write(line) f.close() return HttpResponseRedirect('/face/') def file_download(request): global dirs if request.method=='GET': dirs=request.GET['dirs'] def file_iterator(file_name, chunk_size=512): with open(file_name) as f: while True: c = f.read(chunk_size) if c: yield c else: break the_file_name = dirs response = StreamingHttpResponse(file_iterator(the_file_name)) return response
Android代碼,使用Okhttp進行網絡鏈接app
網絡訪問類:ide
public class HttpUtil { public static void sendOkHttpRequestPost(String address, RequestBody requestBody, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(address) .post(requestBody) .build(); client.newCall(request).enqueue(callback); } public static void sendOkHttpRequestGET(String address, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(address) .build(); client.newCall(request).enqueue(callback); } } public class downloadf { private static downloadf downloadUtil; private final OkHttpClient okHttpClient; public static downloadf get() { if (downloadUtil == null) { downloadUtil = new downloadf(); } return downloadUtil; } private downloadf() { okHttpClient = new OkHttpClient(); } /** * @param url 下載鏈接 * @param saveDir 儲存下載文件的SDCard目錄 * @param listener 下載監聽 */ public void download(final String url, final String saveDir, final OnDownloadListener listener) { Request request = new Request.Builder().url(url).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下載失敗 listener.onDownloadFailed(); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; // 儲存下載文件的目錄 String savePath = isExistDir(saveDir); try { is = response.body().byteStream(); long total = response.body().contentLength(); File file = new File(savePath, getNameFromUrl(url)); fos = new FileOutputStream(file); long sum = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); sum += len; int progress = (int) (sum * 1.0f / total * 100); // 下載中 listener.onDownloading(progress); } fos.flush(); // 下載完成 listener.onDownloadSuccess(); } catch (Exception e) { listener.onDownloadFailed(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } /** * @param saveDir * @return * @throws IOException * 判斷下載目錄是否存在 */ private String isExistDir(String saveDir) throws IOException { // 下載位置 File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); return savePath; } /** * @param url * @return * 從下載鏈接中解析出文件名 */ @NonNull private String getNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } public interface OnDownloadListener { /** * 下載成功 */ void onDownloadSuccess(); /** * @param progress * 下載進度 */ void onDownloading(int progress); /** * 下載失敗 */ void onDownloadFailed(); } }
使用:post
MediaType type = MediaType.parse("application/octet-stream");//"text/xml;charset=utf-8" File file = new File(mDBPath +"/"+name+".data"); File file1=new File(mDBPath+"/face.txt"); RequestBody fileBody = RequestBody.create(type, file); RequestBody fileBody1 = RequestBody.create(type, file1); RequestBody requestBody1 = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("username",name) .addFormDataPart("fileinfo",name+".data",fileBody) .build(); HttpUtil.sendOkHttpRequestPost("http://120.79.51.57:8000/face/posts", requestBody1, new Callback() { @Override public void onFailure(Call call, IOException e) { Log.v("oetrihgdf","失敗"); } @Override public void onResponse(Call call, Response response) throws IOException { Log.v("oifdhdfg","成功"); } }); HttpUtil.sendOkHttpRequestGET("http://120.79.51.57:8000/face/getallface", new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final String responsedata=response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { Gson gson=new Gson(); Facelist facelist= gson.fromJson(responsedata,new TypeToken<Facelist>(){}.getType()); faces.addAll(facelist.getData()); Log.v("faceilist",faces.get(0).getFaceinfo()); for (Face face:faces){ Log.v("orihgdofg",face.getFaceinfo()); downloadf.get().download("http://120.79.51.57:8000/face/filedown?"+"dir="+face.getFaceinfo(), getExternalCacheDir().getPath(), new downloadf.OnDownloadListener() { @Override public void onDownloadSuccess() { Log.v("jmhfgh","下載完成"); //Utils.showToast(MainActivity.this, "下載完成"); } @Override public void onDownloading(int progress) { // progressBar.setProgress(progress); } @Override public void onDownloadFailed() { Log.v("jmhfgh","下載失敗"); // Utils.showToast(MainActivity.this, "下失敗載失敗"); } }); FileInputStream fs = null; try { fs = new FileInputStream(getExternalCacheDir().getPath()+"/"+face.getName()+".data"); ExtInputStream bos = new ExtInputStream(fs); //load version byte[] version_saved = bos.readBytes(); FaceDB.FaceRegist frface = new FaceDB.FaceRegist(face.getName()); AFR_FSDKFace fsdkFace = new AFR_FSDKFace(version_saved); frface.mFaceList.add(fsdkFace); mResgist.add(frface); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }); } });
最後是SDK下載地址:https://ai.arcsoft.com.cn/ucenter/user/reg?utm_source=csdn1&utm_medium=referralui