Participate in a competition to specify the face recognition function with soft rainbow. However, if you want to build your own face database for soft rainbow face recognition, you can only use it offline, you can't always put on a look. Just look at the soft rainbow Demo, and decide to use this simple method to achieve online face recognition:
Android (rainbow soft Demo) takes out face information and name, writes face information to.data file, stores it locally on your phone----> takes out the file and uploads it to Python Djano background, backstage saves the file Exist the project and store the path in the database------> Android accesses the background interface, traverses all file paths in the database, and then accesses the background again as a parameter to get all face information Files and names, when used with the recognition function, can start to compare with all face information, and get results Django background code:
Create a new folder uploads under the project to store face data.data files
For simple implementation, comment in setting.py
#'django.middleware.csrf.CsrfViewMiddleware', Otherwise, the post request will be blocked and it is not recommended that you do the project seriously 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 code, using Okhttp for network connections
Network access class:
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 Download Connection * @param saveDir SDCard directory where downloaded files are stored * @param listener Download Monitor */ 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) { // Download failed 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; // Directory to store downloaded files 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); // Downloading listener.onDownloading(progress); } fos.flush(); // Download complete 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 * Determine if the download directory exists */ private String isExistDir(String saveDir) throws IOException { // Download Location File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); return savePath; } /** * @param url * @return * Resolve file name from download connection */ @NonNull private String getNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } public interface OnDownloadListener { /** * Download Successful */ void onDownloadSuccess(); /** * @param progress * Download Progress */ void onDownloading(int progress); /** * Download failed */ void onDownloadFailed(); } }
Use:
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","fail"); } @Override public void onResponse(Call call, Response response) throws IOException { Log.v("oifdhdfg","Success"); } }); 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","Download complete"); //Utils.showToast(MainActivity.this,'Download complete'); } @Override public void onDownloading(int progress) { // progressBar.setProgress(progress); } @Override public void onDownloadFailed() { Log.v("jmhfgh","Download failed"); // Utils.showToast(MainActivity.this,'Failed Download'); } }); 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(); } } } }); } });
Finally, the SDK download address: https://ai.arcsoft.com.cn/ucenter/user/reg?utm_source=csdn1&utm_medium=referral</facelist>