基于虹软人脸识别Demo android人脸识别

落日映苍穹つ 2022-10-02 00:48 303阅读 0赞

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

参加一个比赛,指定用虹软的人脸识别功能,奈何虹软人脸识别要自己建人脸库,不然就只能离线用,总不能装个样子,简单看了下虹软Demo,下面决定用这种简单方法实现在线人脸识别:

  1. Android端(虹软Demo)取出人脸信息和姓名,人脸信息写入.data文件,存入手机本地------>取出文件上传至Python Djano后台,后台把文件保
  2. 存在工程下并把路径存入数据库------>Android端访问后台接口,遍历所有数据库中文件路径然后作为参数再次访问后台,得到所有人脸信息
  3. 文件和姓名,使用识别功能时,就可以开始和所有人脸信息比对,得到效果
  4. Django 后台代码:

在工程下新建一个文件夹uploads,用来存放人脸数据.data文件

为简单实现,在setting.py中注释

#‘django.middleware.csrf.CsrfViewMiddleware’, 不然post请求被拦截,认真做工程不建议这样做 app.urls:

  1. from django.conf.urls import url, include
  2. from . import views
  3. urlpatterns = [
  4. url(r'^posts',views.posttest),
  5. url(r'^getallface',views.getface),
  6. url(r'^filedown',views.file_download),
  7. ]
  8. views.py
  9. #coding:utf-8
  10. import json
  11. from imp import reload
  12. import sys
  13. import os
  14. from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
  15. from django.shortcuts import render, render_to_response
  16. from django.template import RequestContext
  17. from faceproject.settings import BASE_DIR, MEDIA_ROOT
  18. reload(sys)
  19. from faceapp.models import face, Faceinfos, FaceinfoForm
  20. def getface(request):
  21. if request.method=='GET':
  22. WbAgreementModel = Faceinfos.objects.all()
  23. cflist = []
  24. cfdata = {}
  25. cfdata["coding"] = 1
  26. cfdata['message'] = 'success'
  27. for wam in WbAgreementModel:
  28. wlist = {}
  29. wlist['name'] = wam.username
  30. wlist['faceinfo']=wam.fileinfo
  31. cflist.append(wlist)
  32. cfdata['data'] = cflist
  33. return HttpResponse(json.dumps(cfdata, ensure_ascii=False), content_type="application/json")
  34. def posttest(request):
  35. if request.method=='POST':
  36. files=request.FILES['fileinfo']
  37. if not files:
  38. return HttpResponse("no files for upload!")
  39. Faceinfos(
  40. username=request.POST['username'],
  41. fileinfo=MEDIA_ROOT+'/'+files.name
  42. ).save()
  43. f = open(os.path.join('uploads', files.name), 'wb')
  44. for line in files.chunks():
  45. f.write(line)
  46. f.close()
  47. return HttpResponseRedirect('/face/')
  48. def file_download(request):
  49. global dirs
  50. if request.method=='GET':
  51. dirs=request.GET['dirs']
  52. def file_iterator(file_name, chunk_size=512):
  53. with open(file_name) as f:
  54. while True:
  55. c = f.read(chunk_size)
  56. if c:
  57. yield c
  58. else:
  59. break
  60. the_file_name = dirs
  61. response = StreamingHttpResponse(file_iterator(the_file_name))
  62. return response

Android代码,使用Okhttp进行网络连接

网络访问类:

  1. public class HttpUtil {
  2. public static void sendOkHttpRequestPost(String address, RequestBody requestBody, okhttp3.Callback callback) {
  3. OkHttpClient client = new OkHttpClient();
  4. Request request = new Request.Builder()
  5. .url(address)
  6. .post(requestBody)
  7. .build();
  8. client.newCall(request).enqueue(callback);
  9. }
  10. public static void sendOkHttpRequestGET(String address, okhttp3.Callback callback) {
  11. OkHttpClient client = new OkHttpClient();
  12. Request request = new Request.Builder()
  13. .url(address)
  14. .build();
  15. client.newCall(request).enqueue(callback);
  16. }
  17. }
  18. public class downloadf {
  19. private static downloadf downloadUtil;
  20. private final OkHttpClient okHttpClient;
  21. public static downloadf get() {
  22. if (downloadUtil == null) {
  23. downloadUtil = new downloadf();
  24. }
  25. return downloadUtil;
  26. }
  27. private downloadf() {
  28. okHttpClient = new OkHttpClient();
  29. }
  30. /**
  31. * @param url 下载连接
  32. * @param saveDir 储存下载文件的SDCard目录
  33. * @param listener 下载监听
  34. */
  35. public void download(final String url, final String saveDir, final OnDownloadListener listener) {
  36. Request request = new Request.Builder().url(url).build();
  37. okHttpClient.newCall(request).enqueue(new Callback() {
  38. @Override
  39. public void onFailure(Call call, IOException e) {
  40. // 下载失败
  41. listener.onDownloadFailed();
  42. }
  43. @Override
  44. public void onResponse(Call call, Response response) throws IOException {
  45. InputStream is = null;
  46. byte[] buf = new byte[2048];
  47. int len = 0;
  48. FileOutputStream fos = null;
  49. // 储存下载文件的目录
  50. String savePath = isExistDir(saveDir);
  51. try {
  52. is = response.body().byteStream();
  53. long total = response.body().contentLength();
  54. File file = new File(savePath, getNameFromUrl(url));
  55. fos = new FileOutputStream(file);
  56. long sum = 0;
  57. while ((len = is.read(buf)) != -1) {
  58. fos.write(buf, 0, len);
  59. sum += len;
  60. int progress = (int) (sum * 1.0f / total * 100);
  61. // 下载中
  62. listener.onDownloading(progress);
  63. }
  64. fos.flush();
  65. // 下载完成
  66. listener.onDownloadSuccess();
  67. } catch (Exception e) {
  68. listener.onDownloadFailed();
  69. } finally {
  70. try {
  71. if (is != null)
  72. is.close();
  73. } catch (IOException e) {
  74. }
  75. try {
  76. if (fos != null)
  77. fos.close();
  78. } catch (IOException e) {
  79. }
  80. }
  81. }
  82. });
  83. }
  84. /**
  85. * @param saveDir
  86. * @return
  87. * @throws IOException
  88. * 判断下载目录是否存在
  89. */
  90. private String isExistDir(String saveDir) throws IOException {
  91. // 下载位置
  92. File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
  93. if (!downloadFile.mkdirs()) {
  94. downloadFile.createNewFile();
  95. }
  96. String savePath = downloadFile.getAbsolutePath();
  97. return savePath;
  98. }
  99. /**
  100. * @param url
  101. * @return
  102. * 从下载连接中解析出文件名
  103. */
  104. @NonNull
  105. private String getNameFromUrl(String url) {
  106. return url.substring(url.lastIndexOf("/") + 1);
  107. }
  108. public interface OnDownloadListener {
  109. /**
  110. * 下载成功
  111. */
  112. void onDownloadSuccess();
  113. /**
  114. * @param progress
  115. * 下载进度
  116. */
  117. void onDownloading(int progress);
  118. /**
  119. * 下载失败
  120. */
  121. void onDownloadFailed();
  122. }
  123. }

使用:

  1. MediaType type = MediaType.parse("application/octet-stream");//"text/xml;charset=utf-8"
  2. File file = new File(mDBPath +"/"+name+".data");
  3. File file1=new File(mDBPath+"/face.txt");
  4. RequestBody fileBody = RequestBody.create(type, file);
  5. RequestBody fileBody1 = RequestBody.create(type, file1);
  6. RequestBody requestBody1 = new MultipartBody.Builder()
  7. .setType(MultipartBody.FORM)
  8. .addFormDataPart("username",name)
  9. .addFormDataPart("fileinfo",name+".data",fileBody)
  10. .build();
  11. HttpUtil.sendOkHttpRequestPost("http://120.79.51.57:8000/face/posts", requestBody1, new Callback() {
  12. @Override
  13. public void onFailure(Call call, IOException e) {
  14. Log.v("oetrihgdf","失败");
  15. }
  16. @Override
  17. public void onResponse(Call call, Response response) throws IOException {
  18. Log.v("oifdhdfg","成功");
  19. }
  20. });
  21. HttpUtil.sendOkHttpRequestGET("http://120.79.51.57:8000/face/getallface", new Callback() {
  22. @Override
  23. public void onFailure(Call call, IOException e) {
  24. }
  25. @Override
  26. public void onResponse(Call call, Response response) throws IOException {
  27. final String responsedata=response.body().string();
  28. runOnUiThread(new Runnable() {
  29. @Override
  30. public void run() {
  31. Gson gson=new Gson();
  32. Facelist facelist= gson.fromJson(responsedata,new TypeToken<facelist>(){}.getType());
  33. faces.addAll(facelist.getData());
  34. Log.v("faceilist",faces.get(0).getFaceinfo());
  35. for (Face face:faces){
  36. Log.v("orihgdofg",face.getFaceinfo());
  37. downloadf.get().download("http://120.79.51.57:8000/face/filedown?"+"dir="+face.getFaceinfo(), getExternalCacheDir().getPath(), new downloadf.OnDownloadListener() {
  38. @Override
  39. public void onDownloadSuccess() {
  40. Log.v("jmhfgh","下载完成");
  41. //Utils.showToast(MainActivity.this, "下载完成");
  42. }
  43. @Override
  44. public void onDownloading(int progress) {
  45. // progressBar.setProgress(progress);
  46. }
  47. @Override
  48. public void onDownloadFailed() {
  49. Log.v("jmhfgh","下载失败");
  50. // Utils.showToast(MainActivity.this, "下失败载失败");
  51. }
  52. });
  53. FileInputStream fs = null;
  54. try {
  55. fs = new FileInputStream(getExternalCacheDir().getPath()+"/"+face.getName()+".data");
  56. ExtInputStream bos = new ExtInputStream(fs);
  57. //load version
  58. byte[] version_saved = bos.readBytes();
  59. FaceDB.FaceRegist frface = new FaceDB.FaceRegist(face.getName());
  60. AFR_FSDKFace fsdkFace = new AFR_FSDKFace(version_saved);
  61. frface.mFaceList.add(fsdkFace);
  62. mResgist.add(frface);
  63. } catch (FileNotFoundException e) {
  64. e.printStackTrace();
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70. });
  71. }
  72. });

最后是SDK下载地址:https://ai.arcsoft.com.cn/ucenter/user/reg?utm_source=csdn1&utm_medium=referral

转载于:https://my.oschina.net/u/3970172/blog/3052166

发表评论

表情:
评论列表 (有 0 条评论,303人围观)

还没有评论,来说两句吧...

相关阅读