Android 实例开发基于ArcSoft实现人脸识别
程序员文章站
2022-07-01 09:07:46
目录效果图激活引擎第一步配置app_id和sdk_key第二步:判断是否添加动态链接库(so文件与jar包)第三步:判断是否申明所有权限人脸比对 1:n第一步:初始化本地人脸库第二步:初始化引擎和相机...
效果图
激活引擎
第一步配置app_id和sdk_key
int activecode = faceengine.activeonline( choosefunctionactivity.this, param.app_id, param.sdk_key);
public static final string app_id = "awy6okhqhxtm92yryseqjqwb8ced5hupvyymhk1w7bso"; public static final string sdk_key = "af8salytp3alsmatr55y9uxaykbzjttmt5gwcbkugugh";
第二步:判断是否添加动态链接库(so文件与jar包)
private boolean checksofile(string[] libraries) { file dir = new file(getapplicationinfo().nativelibrarydir); file[] files = dir.listfiles(); if (files == null || files.length == 0) { return false; } list<string> librarynamelist = new arraylist<>(); for (file file : files) { librarynamelist.add(file.getname()); } boolean exists = true; for (string library : libraries) { exists &= librarynamelist.contains(library); } return exists; }
第三步:判断是否申明所有权限
protected boolean checkpermissions(string[] neededpermissions) { if (neededpermissions == null || neededpermissions.length == 0) { return true; } boolean allgranted = true; for (string neededpermission : neededpermissions) { allgranted &= contextcompat.checkselfpermission(this, neededpermission) == packagemanager.permission_granted; } return allgranted; }
激活引擎代码如下
public void activationdevice(final view view) { if (!libraryexists) { showtoast(getstring(r.string.library_not_found)); return; } if (!checkpermissions(needed_permissions)) { activitycompat.requestpermissions(this, needed_permissions, action_request_permissions); return; } if (view != null) { view.setclickable(false); } observable.create( new observableonsubscribe<integer>() { @override public void subscribe(observableemitter<integer> emitter) { runtimeabi runtimeabi = faceengine.getruntimeabi(); log.i(tag, "subscribe: getruntimeabi() " + runtimeabi); long start = system.currenttimemillis(); int activecode = faceengine.activeonline( choosefunctionactivity.this, param.app_id, param.sdk_key); log.i(tag, "subscribe cost: " + (system.currenttimemillis() - start)); emitter.onnext(activecode); } }) .subscribeon( schedulers.io()) .observeon( androidschedulers.mainthread()) .subscribe(new observer<integer>() { @override public void onsubscribe(disposable d) { } @override public void onnext(integer activecode) { if (activecode == errorinfo.mok) { showtoast(getstring(r.string.activation_succeeded)); } else if (activecode == errorinfo.merr_asf_already_activated) { showtoast(getstring(r.string.already_activated)); } else { showtoast(getstring(r.string.active_failed, activecode)); } if (view != null) { view.setclickable(true); } activefileinfo activefileinfo = new activefileinfo(); int res = faceengine.getactivefileinfo(choosefunctionactivity.this, activefileinfo); if (res == errorinfo.mok) { log.i(tag, activefileinfo.tostring()); } } @override public void onerror(throwable e) { showtoast(e.getmessage()); if (view != null) { view.setclickable(true); } } @override public void oncomplete() { } }); }
人脸比对 1:n
第一步:初始化本地人脸库
faceserver.getinstance().init(this);
第二步:初始化引擎和相机
public void ongloballayout() { previewview.getviewtreeobserver().removeongloballayoutlistener(this); if (!checkpermissions(needed_permissions)) { activitycompat.requestpermissions(this, needed_permissions, action_request_permissions); } else { initengine(); initcamera(); } }
第三步:初始化引擎
private void initengine() { ftengine = new faceengine(); ftinitcode = ftengine.init(this, detectmode.asf_detect_mode_video, configutil.getftorient(this), 16, max_detect_num, faceengine.asf_face_detect); frengine = new faceengine(); frinitcode = frengine.init(this, detectmode.asf_detect_mode_image, detectfaceorientpriority.asf_op_0_only, 16, max_detect_num, faceengine.asf_face_recognition); flengine = new faceengine(); flinitcode = flengine.init(this, detectmode.asf_detect_mode_image, detectfaceorientpriority.asf_op_0_only, 16, max_detect_num, faceengine.asf_liveness); log.i(tag, "initengine: init: " + ftinitcode); if (ftinitcode != errorinfo.mok) { string error = getstring(r.string.specific_engine_init_failed, "ftengine", ftinitcode); log.i(tag, "initengine: " + error); showtoast(error); } if (frinitcode != errorinfo.mok) { string error = getstring(r.string.specific_engine_init_failed, "frengine", frinitcode); log.i(tag, "initengine: " + error); showtoast(error); } if (flinitcode != errorinfo.mok) { string error = getstring(r.string.specific_engine_init_failed, "flengine", flinitcode); log.i(tag, "initengine: " + error); showtoast(error); } }
第四步:活体检测
private void initcamera() { displaymetrics metrics = new displaymetrics(); getwindowmanager().getdefaultdisplay().getmetrics(metrics); final facelistener facelistener = new facelistener() { @override public void onfail(exception e) { log.e(tag, "onfail: " + e.getmessage()); } //请求fr的回调 @override public void onfacefeatureinfoget(@nullable final facefeature facefeature, final integer requestid, final integer errorcode) { //fr成功 if (facefeature != null) { // log.i(tag, "onpreview: fr end = " + system.currenttimemillis() + " trackid = " + requestid); integer liveness = livenessmap.get(requestid); //不做活体检测的情况,直接搜索 if (!livenessdetect) { searchface(facefeature, requestid); } //活体检测通过,搜索特征 else if (liveness != null && liveness == livenessinfo.alive) { searchface(facefeature, requestid); } //活体检测未出结果,或者非活体,延迟执行该函数 else { if (requestfeaturestatusmap.containskey(requestid)) { observable.timer(wait_liveness_interval, timeunit.milliseconds) .subscribe(new observer<long>() { disposable disposable; @override public void onsubscribe(disposable d) { disposable = d; getfeaturedelayeddisposables.add(disposable); } @override public void onnext(long along) { onfacefeatureinfoget(facefeature, requestid, errorcode); } @override public void onerror(throwable e) { } @override public void oncomplete() { getfeaturedelayeddisposables.remove(disposable); } }); } } } //特征提取失败 else { if (increaseandgetvalue(extracterrorretrymap, requestid) > max_retry_time) { extracterrorretrymap.put(requestid, 0); string msg; // 传入的faceinfo在指定的图像上无法解析人脸,此处使用的是rgb人脸数据,一般是人脸模糊 if (errorcode != null && errorcode == errorinfo.merr_fsdk_facefeature_low_confidence_level) { msg = getstring(r.string.low_confidence_level); } else { msg = "extractcode:" + errorcode; } facehelper.setname(requestid, getstring(r.string.recognize_failed_notice, msg)); // 在尝试最大次数后,特征提取仍然失败,则认为识别未通过 requestfeaturestatusmap.put(requestid, requestfeaturestatus.failed); retryrecognizedelayed(requestid); } else { requestfeaturestatusmap.put(requestid, requestfeaturestatus.to_retry); } } } @override public void onfacelivenessinfoget(@nullable livenessinfo livenessinfo, final integer requestid, integer errorcode) { if (livenessinfo != null) { int liveness = livenessinfo.getliveness(); livenessmap.put(requestid, liveness); // 非活体,重试 if (liveness == livenessinfo.not_alive) { facehelper.setname(requestid, getstring(r.string.recognize_failed_notice, "not_alive")); // 延迟 fail_retry_interval 后,将该人脸状态置为unknown,帧回调处理时会重新进行活体检测 retrylivenessdetectdelayed(requestid); } } else { if (increaseandgetvalue(livenesserrorretrymap, requestid) > max_retry_time) { livenesserrorretrymap.put(requestid, 0); string msg; // 传入的faceinfo在指定的图像上无法解析人脸,此处使用的是rgb人脸数据,一般是人脸模糊 if (errorcode != null && errorcode == errorinfo.merr_fsdk_facefeature_low_confidence_level) { msg = getstring(r.string.low_confidence_level); } else { msg = "processcode:" + errorcode; } facehelper.setname(requestid, getstring(r.string.recognize_failed_notice, msg)); retrylivenessdetectdelayed(requestid); } else { livenessmap.put(requestid, livenessinfo.unknown); } } } }; cameralistener cameralistener = new cameralistener() { @override public void oncameraopened(camera camera, int cameraid, int displayorientation, boolean ismirror) { camera.size lastpreviewsize = previewsize; previewsize = camera.getparameters().getpreviewsize(); drawhelper = new drawhelper(previewsize.width, previewsize.height, previewview.getwidth(), previewview.getheight(), displayorientation , cameraid, ismirror, false, false); log.i(tag, "oncameraopened: " + drawhelper.tostring()); // 切换相机的时候可能会导致预览尺寸发生变化 if (facehelper == null || lastpreviewsize == null || lastpreviewsize.width != previewsize.width || lastpreviewsize.height != previewsize.height) { integer trackedfacecount = null; // 记录切换时的人脸序号 if (facehelper != null) { trackedfacecount = facehelper.gettrackedfacecount(); facehelper.release(); } facehelper = new facehelper.builder() .ftengine(ftengine) .frengine(frengine) .flengine(flengine) .frqueuesize(max_detect_num) .flqueuesize(max_detect_num) .previewsize(previewsize) .facelistener(facelistener) .trackedfacecount(trackedfacecount == null ? configutil.gettrackedfacecount(facecomparison_rgb.this.getapplicationcontext()) : trackedfacecount) .build(); } } @override public void onpreview(final byte[] nv21, camera camera) { if (facerectview != null) { facerectview.clearfaceinfo(); } list<facepreviewinfo> facepreviewinfolist = facehelper.onpreviewframe(nv21); if (facepreviewinfolist != null && facerectview != null && drawhelper != null) { drawpreviewinfo(facepreviewinfolist); } registerface(nv21, facepreviewinfolist); clearleftface(facepreviewinfolist); if (facepreviewinfolist != null && facepreviewinfolist.size() > 0 && previewsize != null) { for (int i = 0; i < facepreviewinfolist.size(); i++) { integer status = requestfeaturestatusmap.get(facepreviewinfolist.get(i).gettrackid()); /** * 在活体检测开启,在人脸识别状态不为成功或人脸活体状态不为处理中(analyzing)且不为处理完成(alive、not_alive)时重新进行活体检测 */ if (livenessdetect && (status == null || status != requestfeaturestatus.succeed)) { integer liveness = livenessmap.get(facepreviewinfolist.get(i).gettrackid()); if (liveness == null || (liveness != livenessinfo.alive && liveness != livenessinfo.not_alive && liveness != requestlivenessstatus.analyzing)) { livenessmap.put(facepreviewinfolist.get(i).gettrackid(), requestlivenessstatus.analyzing); facehelper.requestfaceliveness(nv21, facepreviewinfolist.get(i).getfaceinfo(), previewsize.width, previewsize.height, faceengine.cp_paf_nv21, facepreviewinfolist.get(i).gettrackid(), livenesstype.rgb); } } /** * 对于每个人脸,若状态为空或者为失败,则请求特征提取(可根据需要添加其他判断以限制特征提取次数), * 特征提取回传的人脸特征结果在{@link facelistener#onfacefeatureinfoget(facefeature, integer, integer)}中回传 */ if (status == null || status == requestfeaturestatus.to_retry) { requestfeaturestatusmap.put(facepreviewinfolist.get(i).gettrackid(), requestfeaturestatus.searching); facehelper.requestfacefeature(nv21, facepreviewinfolist.get(i).getfaceinfo(), previewsize.width, previewsize.height, faceengine.cp_paf_nv21, facepreviewinfolist.get(i).gettrackid()); // log.i(tag, "onpreview: fr start = " + system.currenttimemillis() + " trackid = " + facepreviewinfolist.get(i).gettrackedfacecount()); } } } } @override public void oncameraclosed() { log.i(tag, "oncameraclosed: "); } @override public void oncameraerror(exception e) { log.i(tag, "oncameraerror: " + e.getmessage()); } @override public void oncameraconfigurationchanged(int cameraid, int displayorientation) { if (drawhelper != null) { drawhelper.setcameradisplayorientation(displayorientation); } log.i(tag, "oncameraconfigurationchanged: " + cameraid + " " + displayorientation); } }; camerahelper = new camerahelper.builder() .previewviewsize(new point(previewview.getmeasuredwidth(), previewview.getmeasuredheight())) .rotation(getwindowmanager().getdefaultdisplay().getrotation()) .specificcameraid(rgbcameraid != null ? rgbcameraid : camera.camerainfo.camera_facing_front) .ismirror(false) .previewon(previewview) .cameralistener(cameralistener) .build(); camerahelper.init(); camerahelper.start(); }
人脸注册
private void registerface(final byte[] nv21, final list<facepreviewinfo> facepreviewinfolist) { if (registerstatus == register_status_ready && facepreviewinfolist != null && facepreviewinfolist.size() > 0) { registerstatus = register_status_processing; observable.create( new observableonsubscribe<boolean>() { @override public void subscribe(observableemitter<boolean> emitter) { boolean success = faceserver.getinstance().registernv21(facecomparison_rgb.this, nv21.clone(), previewsize.width, previewsize.height, facepreviewinfolist.get(0).getfaceinfo(), "registered" + facehelper.gettrackedfacecount()); emitter.onnext(success); } }) .subscribeon( schedulers.computation()) .observeon( androidschedulers.mainthread()) .subscribe(new observer<boolean>() { @override public void onsubscribe(disposable d) { } /**判断是否注册成功*/ @override public void onnext(boolean success) { //string result = success ? "register success!" : "register failed!"; //showtoast(result); // alertdialog.builder builder = new alertdialog.builder( facecomparison_rgb.this ); // alertdialog dialog = builder.create(); // view alertdialog_view = view.inflate( facecomparison_rgb.this,r.layout.register_result,null ); // dialog.setview( alertdialog_view ); // dialog.show(); showpopwindows(success); registerstatus = register_status_done; } @override public void onerror(throwable e) { e.printstacktrace(); showtoast("register failed!"); showfailpopwindows(); registerstatus = register_status_done; } @override public void oncomplete() { } }); } }
切换前置、后置摄像头
public void switchcamera(view view) { if (camerahelper != null) { boolean success = camerahelper.switchcamera(); if (!success) { showtoast(getstring(r.string.switch_camera_failed)); } else { showtoast(getstring(r.string.notice_change_detect_degree)); } } }
尾言
本示例工程基于虹软(arcsoft)官方demo改编而成,若有唐突之处,望君海涵
到此这篇关于android 实例开发基于arcsoft实现人脸识别的文章就介绍到这了,更多相关android 人脸识别内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 把平台从机箱拿出来:实测温度明显下降