参加一个比赛,指定用虹软的人脸识别功能,奈何虹软人脸识别要自己建人脸库,不然就只能离线用,总不能装个样子,简单看了下虹软Demo,下面决定用这种简单方法实现在线人脸识别:
Android端(虹软Demo)取出人脸信息和姓名,人脸信息写入.data文件,存入手机本地------>取出文件上传至Python Djano后台,后台把文件保
存在工程下并把路径存入数据库------>Android端访问后台接口,遍历所有数据库中文件路径然后作为参数再次访问后台,得到所有人脸信息
文件和姓名,使用识别功能时,就可以开始和所有人脸信息比对,得到效果
Django 后台代码:
在工程下新建一个文件夹uploads,用来存放人脸数据.data文件
为简单实现,在setting.py中注释
'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进行网络连接
网络访问类:
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();
}
}
使用:
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=referral
网友评论