├── settings.gradle
├── .gitmodules
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── ArcFaceDemo-master
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ └── colors.xml
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ └── layout
│ │ │ ├── dialog_register.xml
│ │ │ ├── item_sample.xml
│ │ │ ├── activity_register.xml
│ │ │ ├── main_test.xml
│ │ │ └── activity_camera.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── arcsoft
│ │ └── sdk_demo
│ │ ├── Application.java
│ │ ├── PermissionAcitivity.java
│ │ ├── FaceDB.java
│ │ ├── MainActivity.java
│ │ ├── DetecterActivity.java
│ │ └── RegisterActivity.java
├── proguard-rules.pro
├── build.gradle
└── .gitignore
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':ArcFaceDemo-master'
2 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "android-extend"]
2 | path = android-extend
3 | url = git://github.com/gqjjqg/android-extend.git
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/asdfqwrasdf/ArcFaceDemo/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | *.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | sdk_demo
3 |
4 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/asdfqwrasdf/ArcFaceDemo/HEAD/ArcFaceDemo-master/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/asdfqwrasdf/ArcFaceDemo/HEAD/ArcFaceDemo-master/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/asdfqwrasdf/ArcFaceDemo/HEAD/ArcFaceDemo-master/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/asdfqwrasdf/ArcFaceDemo/HEAD/ArcFaceDemo-master/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/asdfqwrasdf/ArcFaceDemo/HEAD/ArcFaceDemo-master/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #ff4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Oct 25 14:51:57 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
7 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/layout/dialog_register.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
22 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/layout/item_sample.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
14 |
15 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\android\android_sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/layout/activity_register.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
24 |
25 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 24
5 | buildToolsVersion '28.0.3'
6 | defaultConfig {
7 | applicationId "com.arcsoft.sdk_demo"
8 | minSdkVersion 21
9 | targetSdkVersion 24
10 | versionCode 1
11 | versionName "1.1"
12 | sourceSets.main {
13 | jniLibs.srcDirs = ['libs']
14 | }
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | implementation fileTree(include: ['*.jar'], dir: 'libs')
26 | implementation files('libs/facedetection.jar')
27 | implementation files('libs/facerecognition.jar')
28 | implementation files('libs/facetracking.jar')
29 | implementation files('libs/ageestimation.jar')
30 | implementation files('libs/genderestimation.jar')
31 | implementation 'com.guo.android_extend:android-extend:1.0.6'
32 | }
33 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/layout/main_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
18 |
23 |
24 |
25 |
31 |
36 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/java/com/arcsoft/sdk_demo/Application.java:
--------------------------------------------------------------------------------
1 | package com.arcsoft.sdk_demo;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapFactory;
5 | import android.graphics.Matrix;
6 | import android.media.ExifInterface;
7 | import android.net.Uri;
8 | import android.util.Log;
9 |
10 | /**
11 | * Created by gqj3375 on 2017/4/28.
12 | */
13 |
14 | public class Application extends android.app.Application {
15 | private final String TAG = this.getClass().toString();
16 | FaceDB mFaceDB;
17 | Uri mImage;
18 |
19 | @Override
20 | public void onCreate() {
21 | super.onCreate();
22 | mFaceDB = new FaceDB(this.getExternalCacheDir().getPath());
23 | mImage = null;
24 | }
25 |
26 | public void setCaptureImage(Uri uri) {
27 | mImage = uri;
28 | }
29 |
30 | public Uri getCaptureImage() {
31 | return mImage;
32 | }
33 |
34 | /**
35 | * @param path
36 | * @return
37 | */
38 | public static Bitmap decodeImage(String path) {
39 | Bitmap res;
40 | try {
41 | ExifInterface exif = new ExifInterface(path);
42 | int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
43 |
44 | BitmapFactory.Options op = new BitmapFactory.Options();
45 | op.inSampleSize = 1;
46 | op.inJustDecodeBounds = false;
47 | //op.inMutable = true;
48 | res = BitmapFactory.decodeFile(path, op);
49 | //rotate and scale.
50 | Matrix matrix = new Matrix();
51 |
52 | if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
53 | matrix.postRotate(90);
54 | } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
55 | matrix.postRotate(180);
56 | } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
57 | matrix.postRotate(270);
58 | }
59 |
60 | Bitmap temp = Bitmap.createBitmap(res, 0, 0, res.getWidth(), res.getHeight(), matrix, true);
61 | Log.d("com.arcsoft", "check target Image:" + temp.getWidth() + "X" + temp.getHeight());
62 |
63 | if (!temp.equals(res)) {
64 | res.recycle();
65 | }
66 | return temp;
67 | } catch (Exception e) {
68 | e.printStackTrace();
69 | }
70 | return null;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ArcFaceDemo
2 | Free SDK demo
3 |
4 | >工程如何使用?
5 | 1. 下载代码:
6 | git clone https://github.com/asdfqwrasdf/ArcFaceDemo.git 或者直接下载压缩包
7 |
8 | 2. 前往[官网](http://www.arcsoft.com.cn/ai/arcface.html)申请appid和sdkkey。
9 | **注意:当前版本请下载ArcFace1.2**
10 | 修改 ArcFaceDemo-master\src\main\java\com\arcsoft\sdk_demo\FaceDB.java 下面的对应的值:
11 |
12 | ```java
13 | public static String appid = "xxxx";
14 | public static String fd_key = "xxxx";
15 | public static String ft_key = "xxxx";
16 | public static String fr_key = "xxxx";
17 | public static String age_key = "xxxx";
18 | public static String gender_key = "xxxx";
19 | ```
20 | 3. 下载sdk包之后,解压各个包里libs中的文件到 ArcFaceDemo-master\libs 下,同名so直接覆盖。
21 |
22 | 4. Android Studio3.x 中直接打开或者导入Project,编译运行即可。
23 |
24 | > demo如何使用?
25 |
26 | 1. 点击第一个按钮 打开图片或者拍一张带人脸的照片,确认后自动执行人脸,弹出注册框,注册第一个人脸。
27 | 注册界面底部会展示已注册的信息列表,点击列表项,则可以执行删除操作。
28 | 2. 点击第二个按钮 选择打开前置或者后置的镜头进行检测。
29 |
30 | > demo中人脸数据的保存方式?
31 |
32 | 以注册时人名为关键索引,保存在face.txt中。
33 | 创建的 name.data 则为实际的数据存储文件,保存了所有特征信息。
34 | 同一个名字可以注册多个不同状态角度的人脸,在name.data 中连续保存,占用的数据文件长度为:
35 | N * {4字节(特征数据长度) + 22020字节(特征数据信息)}
36 |
37 | > 最低支持的API-LEVEL?
38 |
39 | 14-27
40 |
41 | ---------------
42 | > Issue Report
43 | 1. before report
44 | please check the closed issues.
45 |
46 | 2. issue format
47 | a.错误信息:log,input image,core stack, etc...
48 | b.设备信息:cpu, memory, device name, etc...
49 | c.系统版本:OS version, API leve,etc...
50 | d.具体操作流程:which step,how to recurrence,etc...
51 |
52 | ---------------
53 | > FAQ
54 | 1. Gradle 错误提示 Error:Failed to find target with hash string 'android-24'.......
55 | 一般Android Studio 窗口会有个链接(Install missing platform(s) and sync project)
56 | 点击下载更新 android-24 即可解决(其他版本没测试过,建议不要随意更改)。
57 |
58 | 2. 加载图片注册时Crash.
59 | NV21格式限制高度和宽度不能同时为奇数,demo已经对这个做了保护。
60 | 如有发生,请提供图像尺寸和发生时的全部log。
61 |
62 | 3. 年龄和性别检测结果准确度不够.
63 | Video的接口性能优先,Image的接口准确度优先。
64 |
65 | 4. com.guo.android_extend:android-extend 找不到依赖.
66 | 此第三方库[android_extend](https://github.com/gqjjqg/android-extend) 用来简化camera调用,提供简单的工具方便demo开发。
67 | 一般android studio会自动从jcenter 下载对应的aar包,如果没有自动下载,请自行检查是否网络问题,或者删掉build等编译目录,重新运行gradle.
68 |
69 | 5. 还有其他问题.
70 | 直接提交[issue](https://github.com/asdfqwrasdf/ArcFaceDemo/issues)
71 | 我们会尽快解决
72 |
73 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/res/layout/activity_camera.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
17 |
18 |
24 |
25 |
35 |
36 |
46 |
47 |
59 |
60 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/java/com/arcsoft/sdk_demo/PermissionAcitivity.java:
--------------------------------------------------------------------------------
1 | package com.arcsoft.sdk_demo;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.app.ProgressDialog;
6 | import android.content.Intent;
7 | import android.content.pm.PackageManager;
8 | import android.os.Bundle;
9 | import android.os.Handler;
10 | import android.os.Process;
11 | import android.widget.Toast;
12 |
13 | import java.util.ArrayList;
14 | import java.util.List;
15 |
16 | /**
17 | * Created by gqj3375 on 2017/2/24.
18 | */
19 |
20 | public class PermissionAcitivity extends Activity {
21 | public static int PERMISSION_REQ = 0x123456;
22 |
23 | private String[] mPermission = new String[] {
24 | Manifest.permission.INTERNET,
25 | Manifest.permission.CAMERA,
26 | Manifest.permission.WRITE_EXTERNAL_STORAGE
27 | };
28 |
29 | private List mRequestPermission = new ArrayList();
30 |
31 | /* (non-Javadoc)
32 | * @see android.app.Activity#onCreate(android.os.Bundle)
33 | */
34 | ;@Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | // TODO Auto-generated method stub
37 | super.onCreate(savedInstanceState);
38 |
39 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
40 | for (String one : mPermission) {
41 | if (PackageManager.PERMISSION_GRANTED != this.checkPermission(one, Process.myPid(), Process.myUid())) {
42 | mRequestPermission.add(one);
43 | }
44 | }
45 | if (!mRequestPermission.isEmpty()) {
46 | this.requestPermissions(mRequestPermission.toArray(new String[mRequestPermission.size()]), PERMISSION_REQ);
47 | return ;
48 | }
49 | }
50 | startActiviy();
51 | }
52 |
53 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
54 | // 版本兼容
55 | if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
56 | return;
57 | }
58 | if (requestCode == PERMISSION_REQ) {
59 | for (int i = 0; i < grantResults.length; i++) {
60 | for (String one : mPermission) {
61 | if (permissions[i].equals(one) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
62 | mRequestPermission.remove(one);
63 | }
64 | }
65 | }
66 | startActiviy();
67 | }
68 | }
69 |
70 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
71 | if (requestCode == PERMISSION_REQ) {
72 | if (resultCode == 0) {
73 | this.finish();
74 | }
75 | }
76 | }
77 |
78 | public void startActiviy() {
79 | if (mRequestPermission.isEmpty()) {
80 | final ProgressDialog mProgressDialog = new ProgressDialog(this);
81 | mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
82 | mProgressDialog.setTitle("loading register data...");
83 | mProgressDialog.setCancelable(false);
84 | mProgressDialog.show();
85 | new Thread(new Runnable() {
86 | @Override
87 | public void run() {
88 | Application app = (Application) PermissionAcitivity.this.getApplicationContext();
89 | app.mFaceDB.loadFaces();
90 | PermissionAcitivity.this.runOnUiThread(new Runnable() {
91 | @Override
92 | public void run() {
93 | mProgressDialog.cancel();
94 | Intent intent = new Intent(PermissionAcitivity.this, MainActivity.class);
95 | startActivityForResult(intent, PERMISSION_REQ);
96 | }
97 | });
98 | }
99 | }).start();
100 | } else {
101 | Toast.makeText(this, "PERMISSION DENIED!", Toast.LENGTH_LONG).show();
102 | new Handler().postDelayed(new Runnable() {
103 | @Override
104 | public void run() {
105 | PermissionAcitivity.this.finish();
106 | }
107 | }, 3000);
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/.gitignore:
--------------------------------------------------------------------------------
1 | #################
2 | ## Eclipse
3 | #################
4 | *.pydevproject
5 | .project
6 | .metadata
7 | bin/
8 | tmp/
9 | gen/
10 | *.tmp
11 | *.bak
12 | *.swp
13 | *~.nib
14 | local.properties
15 | .classpath
16 | .settings/
17 | .loadpath
18 | *.sln
19 | *.o
20 | *.d
21 | #*.so
22 | *.mk
23 | client*
24 | asnode
25 | # External tool builders
26 | .externalToolBuilders/
27 |
28 | # Locally stored "Eclipse launch configurations"
29 | *.launch
30 |
31 | # CDT-specific
32 | .cproject
33 |
34 | # PDT-specific
35 | .buildpath
36 |
37 |
38 | #################
39 | ## Visual Studio
40 | #################
41 |
42 | ## Ignore Visual Studio temporary files, build results, and
43 | ## files generated by popular Visual Studio add-ons.
44 |
45 | # User-specific files
46 | *.suo
47 | *.user
48 | *.sln.docstates
49 |
50 | # Build results
51 | [Dd]ebug/
52 | [Rr]elease/
53 | x64/
54 | build/
55 | [Bb]in/
56 | [Oo]bj/
57 |
58 | # MSTest test Results
59 | [Tt]est[Rr]esult*/
60 | [Bb]uild[Ll]og.*
61 |
62 | *_i.c
63 | *_p.c
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.pch
68 | *.pdb
69 | *.pgc
70 | *.pgd
71 | *.rsp
72 | *.sbr
73 | *.tlb
74 | *.tli
75 | *.tlh
76 | *.tmp
77 | *.tmp_proj
78 | *.log
79 | *.vspscc
80 | *.vssscc
81 | .builds
82 | *.pidb
83 | *.log
84 | *.scc
85 |
86 | # Visual C++ cache files
87 | ipch/
88 | *.aps
89 | *.ncb
90 | *.opensdf
91 | *.sdf
92 | *.cachefile
93 |
94 | # Visual Studio profiler
95 | *.psess
96 | *.vsp
97 | *.vspx
98 |
99 | # Guidance Automation Toolkit
100 | *.gpState
101 |
102 | # ReSharper is a .NET coding add-in
103 | _ReSharper*/
104 | *.[Rr]e[Ss]harper
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | *.ncrunch*
114 | .*crunch*.local.xml
115 |
116 | # Installshield output folder
117 | [Ee]xpress/
118 |
119 | # DocProject is a documentation generator add-in
120 | DocProject/buildhelp/
121 | DocProject/Help/*.HxT
122 | DocProject/Help/*.HxC
123 | DocProject/Help/*.hhc
124 | DocProject/Help/*.hhk
125 | DocProject/Help/*.hhp
126 | DocProject/Help/Html2
127 | DocProject/Help/html
128 |
129 | # Click-Once directory
130 | publish/
131 |
132 | # Publish Web Output
133 | *.Publish.xml
134 | *.pubxml
135 |
136 | # NuGet Packages Directory
137 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line
138 | #packages/
139 |
140 | # Windows Azure Build Output
141 | csx
142 | *.build.csdef
143 |
144 | # Windows Store app package directory
145 | AppPackages/
146 |
147 | # Others
148 | sql/
149 | *.Cache
150 | ClientBin/
151 | [Ss]tyle[Cc]op.*
152 | ~$*
153 | *~
154 | *.dbmdl
155 | *.[Pp]ublish.xml
156 | *.pfx
157 | *.publishsettings
158 |
159 | # RIA/Silverlight projects
160 | Generated_Code/
161 |
162 | # Backup & report files from converting an old project file to a newer
163 | # Visual Studio version. Backup files are not needed, because we have git ;-)
164 | _UpgradeReport_Files/
165 | Backup*/
166 | UpgradeLog*.XML
167 | UpgradeLog*.htm
168 |
169 | # SQL Server files
170 | App_Data/*.mdf
171 | App_Data/*.ldf
172 |
173 | #############
174 | ## Windows detritus
175 | #############
176 |
177 | # Windows image file caches
178 | Thumbs.db
179 | ehthumbs.db
180 |
181 | # Folder config file
182 | Desktop.ini
183 |
184 | # Recycle Bin used on file shares
185 | $RECYCLE.BIN/
186 |
187 | # Mac crap
188 | .DS_Store
189 |
190 | #SVN
191 | .svn
192 |
193 | #############
194 | ## Python
195 | #############
196 |
197 | *.py[co]
198 |
199 | # Packages
200 | *.egg
201 | *.egg-info
202 | dist/
203 | build/
204 | eggs/
205 | parts/
206 | var/
207 | sdist/
208 | develop-eggs/
209 | .installed.cfg
210 |
211 | # Installer logs
212 | pip-log.txt
213 |
214 | # Unit test / coverage reports
215 | .coverage
216 | .tox
217 |
218 | #Translations
219 | *.mo
220 |
221 | #Mr Developer
222 | .mr.developer.cfg
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/java/com/arcsoft/sdk_demo/FaceDB.java:
--------------------------------------------------------------------------------
1 | package com.arcsoft.sdk_demo;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapFactory;
5 | import android.util.Log;
6 |
7 | import com.arcsoft.facerecognition.AFR_FSDKEngine;
8 | import com.arcsoft.facerecognition.AFR_FSDKError;
9 | import com.arcsoft.facerecognition.AFR_FSDKFace;
10 | import com.arcsoft.facerecognition.AFR_FSDKVersion;
11 | import com.guo.android_extend.java.ExtInputStream;
12 | import com.guo.android_extend.java.ExtOutputStream;
13 |
14 | import java.io.File;
15 | import java.io.FileInputStream;
16 | import java.io.FileNotFoundException;
17 | import java.io.FileOutputStream;
18 | import java.io.IOException;
19 | import java.io.OutputStream;
20 | import java.util.ArrayList;
21 | import java.util.LinkedHashMap;
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | /**
26 | * Created by gqj3375 on 2017/7/11.
27 | */
28 |
29 | public class FaceDB {
30 | private final String TAG = this.getClass().toString();
31 |
32 | public static String appid = "xxx";
33 | public static String ft_key = "xxx";
34 | public static String fd_key = "xxx";
35 | public static String fr_key = "xxx";
36 | public static String age_key = "xxx";
37 | public static String gender_key = "xxx";
38 |
39 | String mDBPath;
40 | List mRegister;
41 | AFR_FSDKEngine mFREngine;
42 | AFR_FSDKVersion mFRVersion;
43 | boolean mUpgrade;
44 |
45 | class FaceRegist {
46 | String mName;
47 | Map mFaceList;
48 |
49 | public FaceRegist(String name) {
50 | mName = name;
51 | mFaceList = new LinkedHashMap<>();
52 | }
53 | }
54 |
55 | public FaceDB(String path) {
56 | mDBPath = path;
57 | mRegister = new ArrayList<>();
58 | mFRVersion = new AFR_FSDKVersion();
59 | mUpgrade = false;
60 | mFREngine = new AFR_FSDKEngine();
61 | AFR_FSDKError error = mFREngine.AFR_FSDK_InitialEngine(FaceDB.appid, FaceDB.fr_key);
62 | if (error.getCode() != AFR_FSDKError.MOK) {
63 | Log.e(TAG, "AFR_FSDK_InitialEngine fail! error code :" + error.getCode());
64 | } else {
65 | mFREngine.AFR_FSDK_GetVersion(mFRVersion);
66 | Log.d(TAG, "AFR_FSDK_GetVersion=" + mFRVersion.toString());
67 | }
68 | }
69 |
70 | public void destroy() {
71 | if (mFREngine != null) {
72 | mFREngine.AFR_FSDK_UninitialEngine();
73 | }
74 | }
75 |
76 | private boolean saveInfo() {
77 | try {
78 | FileOutputStream fs = new FileOutputStream(mDBPath + "/face.txt");
79 | ExtOutputStream bos = new ExtOutputStream(fs);
80 | bos.writeString(mFRVersion.toString() + "," + mFRVersion.getFeatureLevel());
81 | bos.close();
82 | fs.close();
83 | return true;
84 | } catch (FileNotFoundException e) {
85 | e.printStackTrace();
86 | } catch (IOException e) {
87 | e.printStackTrace();
88 | }
89 | return false;
90 | }
91 |
92 | private boolean loadInfo() {
93 | if (!mRegister.isEmpty()) {
94 | return false;
95 | }
96 | try {
97 | FileInputStream fs = new FileInputStream(mDBPath + "/face.txt");
98 | ExtInputStream bos = new ExtInputStream(fs);
99 | //load version
100 | String version_saved = bos.readString();
101 | if (version_saved.equals(mFRVersion.toString() + "," + mFRVersion.getFeatureLevel())) {
102 | mUpgrade = true;
103 | }
104 | //load all regist name.
105 | if (version_saved != null) {
106 | for (String name = bos.readString(); name != null; name = bos.readString()){
107 | if (new File(mDBPath + "/" + name + ".data").exists()) {
108 | mRegister.add(new FaceRegist(new String(name)));
109 | }
110 | }
111 | }
112 | bos.close();
113 | fs.close();
114 | return true;
115 | } catch (FileNotFoundException e) {
116 | e.printStackTrace();
117 | } catch (IOException e) {
118 | e.printStackTrace();
119 | }
120 | return false;
121 | }
122 |
123 | public boolean loadFaces(){
124 | if (loadInfo()) {
125 | try {
126 | for (FaceRegist face : mRegister) {
127 | Log.d(TAG, "load name:" + face.mName + "'s face feature data.");
128 | FileInputStream fs = new FileInputStream(mDBPath + "/" + face.mName + ".data");
129 | ExtInputStream bos = new ExtInputStream(fs);
130 | AFR_FSDKFace afr = null;
131 | do {
132 | if (afr != null) {
133 | if (mUpgrade) {
134 | //upgrade data.
135 | }
136 | String keyFile = bos.readString();
137 | face.mFaceList.put(keyFile, afr);
138 | }
139 | afr = new AFR_FSDKFace();
140 | } while (bos.readBytes(afr.getFeatureData()));
141 | bos.close();
142 | fs.close();
143 | Log.d(TAG, "load name: size = " + face.mFaceList.size());
144 | }
145 | return true;
146 | } catch (FileNotFoundException e) {
147 | e.printStackTrace();
148 | } catch (IOException e) {
149 | e.printStackTrace();
150 | }
151 | }
152 | return false;
153 | }
154 |
155 | public void addFace(String name, AFR_FSDKFace face, Bitmap faceicon) {
156 | try {
157 | // save face
158 | String keyPath = mDBPath + "/" + System.nanoTime() + ".jpg";
159 | File keyFile = new File(keyPath);
160 | OutputStream stream = new FileOutputStream(keyFile);
161 | if (faceicon.compress(Bitmap.CompressFormat.JPEG, 80, stream)) {
162 | Log.d(TAG, "saved face bitmap to jpg!");
163 | }
164 | stream.close();
165 |
166 | //check if already registered.
167 | boolean add = true;
168 | for (FaceRegist frface : mRegister) {
169 | if (frface.mName.equals(name)) {
170 | frface.mFaceList.put(keyPath, face);
171 | add = false;
172 | break;
173 | }
174 | }
175 | if (add) { // not registered.
176 | FaceRegist frface = new FaceRegist(name);
177 | frface.mFaceList.put(keyPath, face);
178 | mRegister.add(frface);
179 | }
180 |
181 | if (saveInfo()) {
182 | //update all names
183 | FileOutputStream fs = new FileOutputStream(mDBPath + "/face.txt", true);
184 | ExtOutputStream bos = new ExtOutputStream(fs);
185 | for (FaceRegist frface : mRegister) {
186 | bos.writeString(frface.mName);
187 | }
188 | bos.close();
189 | fs.close();
190 |
191 | //save new feature
192 | fs = new FileOutputStream(mDBPath + "/" + name + ".data", true);
193 | bos = new ExtOutputStream(fs);
194 | bos.writeBytes(face.getFeatureData());
195 | bos.writeString(keyPath);
196 | bos.close();
197 | fs.close();
198 | }
199 | } catch (FileNotFoundException e) {
200 | e.printStackTrace();
201 | } catch (IOException e) {
202 | e.printStackTrace();
203 | }
204 | }
205 |
206 | public boolean delete(String name) {
207 | try {
208 | //check if already registered.
209 | boolean find = false;
210 | for (FaceRegist frface : mRegister) {
211 | if (frface.mName.equals(name)) {
212 | File delfile = new File(mDBPath + "/" + name + ".data");
213 | if (delfile.exists()) {
214 | delfile.delete();
215 | }
216 | mRegister.remove(frface);
217 | find = true;
218 | break;
219 | }
220 | }
221 |
222 | if (find) {
223 | if (saveInfo()) {
224 | //update all names
225 | FileOutputStream fs = new FileOutputStream(mDBPath + "/face.txt", true);
226 | ExtOutputStream bos = new ExtOutputStream(fs);
227 | for (FaceRegist frface : mRegister) {
228 | bos.writeString(frface.mName);
229 | }
230 | bos.close();
231 | fs.close();
232 | }
233 | }
234 | return find;
235 | } catch (FileNotFoundException e) {
236 | e.printStackTrace();
237 | } catch (IOException e) {
238 | e.printStackTrace();
239 | }
240 | return false;
241 | }
242 |
243 | public boolean upgrade() {
244 | return false;
245 | }
246 | }
247 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/java/com/arcsoft/sdk_demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.arcsoft.sdk_demo;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.ContentUris;
6 | import android.content.ContentValues;
7 | import android.content.Context;
8 | import android.content.DialogInterface;
9 | import android.content.Intent;
10 | import android.database.Cursor;
11 | import android.graphics.Bitmap;
12 | import android.net.Uri;
13 | import android.os.Build;
14 | import android.os.Bundle;
15 | import android.os.Environment;
16 | import android.provider.DocumentsContract;
17 | import android.provider.MediaStore;
18 | import android.util.Log;
19 | import android.view.View;
20 | import android.view.View.OnClickListener;
21 | import android.widget.Toast;
22 |
23 | public class MainActivity extends Activity implements OnClickListener {
24 | private final String TAG = this.getClass().toString();
25 |
26 | private static final int REQUEST_CODE_IMAGE_CAMERA = 1;
27 | private static final int REQUEST_CODE_IMAGE_OP = 2;
28 | private static final int REQUEST_CODE_OP = 3;
29 |
30 | /* (non-Javadoc)
31 | * @see android.app.Activity#onCreate(android.os.Bundle)
32 | */
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | // TODO Auto-generated method stub
36 | super.onCreate(savedInstanceState);
37 | this.setContentView(R.layout.main_test);
38 | View v = this.findViewById(R.id.button1);
39 | v.setOnClickListener(this);
40 | v = this.findViewById(R.id.button2);
41 | v.setOnClickListener(this);
42 | }
43 |
44 | /* (non-Javadoc)
45 | * @see android.app.Activity#onDestroy()
46 | */
47 | @Override
48 | protected void onDestroy() {
49 | // TODO Auto-generated method stub
50 | super.onDestroy();
51 | }
52 |
53 | @Override
54 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
55 | super.onActivityResult(requestCode, resultCode, data);
56 |
57 | if (requestCode == REQUEST_CODE_IMAGE_OP && resultCode == RESULT_OK) {
58 | Uri mPath = data.getData();
59 | String file = getPath(mPath);
60 | Bitmap bmp = Application.decodeImage(file);
61 | if (bmp == null || bmp.getWidth() <= 0 || bmp.getHeight() <= 0 ) {
62 | Log.e(TAG, "error");
63 | } else {
64 | Log.i(TAG, "bmp [" + bmp.getWidth() + "," + bmp.getHeight());
65 | }
66 | startRegister(bmp, file);
67 | } else if (requestCode == REQUEST_CODE_OP) {
68 | Log.i(TAG, "RESULT =" + resultCode);
69 | if (data == null) {
70 | return;
71 | }
72 | Bundle bundle = data.getExtras();
73 | String path = bundle.getString("imagePath");
74 | Log.i(TAG, "path="+path);
75 | } else if (requestCode == REQUEST_CODE_IMAGE_CAMERA && resultCode == RESULT_OK) {
76 | Uri mPath = ((Application)(MainActivity.this.getApplicationContext())).getCaptureImage();
77 | String file = getPath(mPath);
78 | Bitmap bmp = Application.decodeImage(file);
79 | startRegister(bmp, file);
80 | }
81 | }
82 |
83 | @Override
84 | public void onClick(View paramView) {
85 | // TODO Auto-generated method stub
86 | switch (paramView.getId()) {
87 | case R.id.button2:
88 | if( ((Application)getApplicationContext()).mFaceDB.mRegister.isEmpty() ) {
89 | Toast.makeText(this, "没有注册人脸,请先注册!", Toast.LENGTH_SHORT).show();
90 | } else {
91 | new AlertDialog.Builder(this)
92 | .setTitle("请选择相机")
93 | .setIcon(android.R.drawable.ic_dialog_info)
94 | .setItems(new String[]{"后置相机", "前置相机"}, new DialogInterface.OnClickListener() {
95 | @Override
96 | public void onClick(DialogInterface dialog, int which) {
97 | startDetector(which);
98 | }
99 | })
100 | .show();
101 | }
102 | break;
103 | case R.id.button1:
104 | new AlertDialog.Builder(this)
105 | .setTitle("请选择注册方式")
106 | .setIcon(android.R.drawable.ic_dialog_info)
107 | .setItems(new String[]{"打开图片", "拍摄照片"}, new DialogInterface.OnClickListener() {
108 | @Override
109 | public void onClick(DialogInterface dialog, int which) {
110 | switch (which){
111 | case 1:
112 | Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
113 | ContentValues values = new ContentValues(1);
114 | values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
115 | Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
116 | ((Application)(MainActivity.this.getApplicationContext())).setCaptureImage(uri);
117 | intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
118 | startActivityForResult(intent, REQUEST_CODE_IMAGE_CAMERA);
119 | break;
120 | case 0:
121 | Intent getImageByalbum = new Intent(Intent.ACTION_GET_CONTENT);
122 | getImageByalbum.addCategory(Intent.CATEGORY_OPENABLE);
123 | getImageByalbum.setType("image/jpeg");
124 | startActivityForResult(getImageByalbum, REQUEST_CODE_IMAGE_OP);
125 | break;
126 | default:;
127 | }
128 | }
129 | })
130 | .show();
131 | break;
132 | default:;
133 | }
134 | }
135 |
136 | /**
137 | * @param uri
138 | * @return
139 | */
140 | private String getPath(Uri uri) {
141 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
142 | if (DocumentsContract.isDocumentUri(this, uri)) {
143 | // ExternalStorageProvider
144 | if (isExternalStorageDocument(uri)) {
145 | final String docId = DocumentsContract.getDocumentId(uri);
146 | final String[] split = docId.split(":");
147 | final String type = split[0];
148 |
149 | if ("primary".equalsIgnoreCase(type)) {
150 | return Environment.getExternalStorageDirectory() + "/" + split[1];
151 | }
152 |
153 | // TODO handle non-primary volumes
154 | } else if (isDownloadsDocument(uri)) {
155 |
156 | final String id = DocumentsContract.getDocumentId(uri);
157 | final Uri contentUri = ContentUris.withAppendedId(
158 | Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
159 |
160 | return getDataColumn(this, contentUri, null, null);
161 | } else if (isMediaDocument(uri)) {
162 | final String docId = DocumentsContract.getDocumentId(uri);
163 | final String[] split = docId.split(":");
164 | final String type = split[0];
165 |
166 | Uri contentUri = null;
167 | if ("image".equals(type)) {
168 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
169 | } else if ("video".equals(type)) {
170 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
171 | } else if ("audio".equals(type)) {
172 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
173 | }
174 |
175 | final String selection = "_id=?";
176 | final String[] selectionArgs = new String[] {
177 | split[1]
178 | };
179 |
180 | return getDataColumn(this, contentUri, selection, selectionArgs);
181 | }
182 | }
183 | }
184 | String[] proj = { MediaStore.Images.Media.DATA };
185 | Cursor actualimagecursor = this.getContentResolver().query(uri, proj, null, null, null);
186 | int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
187 | actualimagecursor.moveToFirst();
188 | String img_path = actualimagecursor.getString(actual_image_column_index);
189 | String end = img_path.substring(img_path.length() - 4);
190 | if (0 != end.compareToIgnoreCase(".jpg") && 0 != end.compareToIgnoreCase(".png")) {
191 | return null;
192 | }
193 | return img_path;
194 | }
195 |
196 | /**
197 | * @param uri The Uri to check.
198 | * @return Whether the Uri authority is ExternalStorageProvider.
199 | */
200 | public static boolean isExternalStorageDocument(Uri uri) {
201 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
202 | }
203 |
204 | /**
205 | * @param uri The Uri to check.
206 | * @return Whether the Uri authority is DownloadsProvider.
207 | */
208 | public static boolean isDownloadsDocument(Uri uri) {
209 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
210 | }
211 |
212 | /**
213 | * @param uri The Uri to check.
214 | * @return Whether the Uri authority is MediaProvider.
215 | */
216 | public static boolean isMediaDocument(Uri uri) {
217 | return "com.android.providers.media.documents".equals(uri.getAuthority());
218 | }
219 |
220 | /**
221 | * Get the value of the data column for this Uri. This is useful for
222 | * MediaStore Uris, and other file-based ContentProviders.
223 | *
224 | * @param context The context.
225 | * @param uri The Uri to query.
226 | * @param selection (Optional) Filter used in the query.
227 | * @param selectionArgs (Optional) Selection arguments used in the query.
228 | * @return The value of the _data column, which is typically a file path.
229 | */
230 | public static String getDataColumn(Context context, Uri uri, String selection,
231 | String[] selectionArgs) {
232 |
233 | Cursor cursor = null;
234 | final String column = "_data";
235 | final String[] projection = {
236 | column
237 | };
238 |
239 | try {
240 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
241 | null);
242 | if (cursor != null && cursor.moveToFirst()) {
243 | final int index = cursor.getColumnIndexOrThrow(column);
244 | return cursor.getString(index);
245 | }
246 | } finally {
247 | if (cursor != null)
248 | cursor.close();
249 | }
250 | return null;
251 | }
252 |
253 | /**
254 | * @param mBitmap
255 | */
256 | private void startRegister(Bitmap mBitmap, String file) {
257 | Intent it = new Intent(MainActivity.this, RegisterActivity.class);
258 | Bundle bundle = new Bundle();
259 | bundle.putString("imagePath", file);
260 | it.putExtras(bundle);
261 | startActivityForResult(it, REQUEST_CODE_OP);
262 | }
263 |
264 | private void startDetector(int camera) {
265 | Intent it = new Intent(MainActivity.this, DetecterActivity.class);
266 | it.putExtra("Camera", camera);
267 | startActivityForResult(it, REQUEST_CODE_OP);
268 | }
269 |
270 | }
271 |
272 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/java/com/arcsoft/sdk_demo/DetecterActivity.java:
--------------------------------------------------------------------------------
1 | package com.arcsoft.sdk_demo;
2 |
3 | import android.app.Activity;
4 | import android.graphics.Bitmap;
5 | import android.graphics.BitmapFactory;
6 | import android.graphics.Color;
7 | import android.graphics.ImageFormat;
8 | import android.graphics.Rect;
9 | import android.graphics.YuvImage;
10 | import android.hardware.Camera;
11 | import android.os.Bundle;
12 | import android.os.Handler;
13 | import android.util.Log;
14 | import android.view.MotionEvent;
15 | import android.view.View;
16 | import android.widget.ImageButton;
17 | import android.widget.ImageView;
18 | import android.widget.TextView;
19 |
20 | import com.arcsoft.ageestimation.ASAE_FSDKAge;
21 | import com.arcsoft.ageestimation.ASAE_FSDKEngine;
22 | import com.arcsoft.ageestimation.ASAE_FSDKError;
23 | import com.arcsoft.ageestimation.ASAE_FSDKFace;
24 | import com.arcsoft.ageestimation.ASAE_FSDKVersion;
25 | import com.arcsoft.facerecognition.AFR_FSDKEngine;
26 | import com.arcsoft.facerecognition.AFR_FSDKError;
27 | import com.arcsoft.facerecognition.AFR_FSDKFace;
28 | import com.arcsoft.facerecognition.AFR_FSDKMatching;
29 | import com.arcsoft.facerecognition.AFR_FSDKVersion;
30 | import com.arcsoft.facetracking.AFT_FSDKEngine;
31 | import com.arcsoft.facetracking.AFT_FSDKError;
32 | import com.arcsoft.facetracking.AFT_FSDKFace;
33 | import com.arcsoft.facetracking.AFT_FSDKVersion;
34 | import com.arcsoft.genderestimation.ASGE_FSDKEngine;
35 | import com.arcsoft.genderestimation.ASGE_FSDKError;
36 | import com.arcsoft.genderestimation.ASGE_FSDKFace;
37 | import com.arcsoft.genderestimation.ASGE_FSDKGender;
38 | import com.arcsoft.genderestimation.ASGE_FSDKVersion;
39 | import com.guo.android_extend.GLES2Render;
40 | import com.guo.android_extend.java.AbsLoop;
41 | import com.guo.android_extend.java.ExtByteArrayOutputStream;
42 | import com.guo.android_extend.tools.CameraHelper;
43 | import com.guo.android_extend.widget.CameraFrameData;
44 | import com.guo.android_extend.widget.CameraGLSurfaceView;
45 | import com.guo.android_extend.widget.CameraSurfaceView;
46 | import com.guo.android_extend.widget.CameraSurfaceView.OnCameraListener;
47 |
48 | import java.io.IOException;
49 | import java.util.ArrayList;
50 | import java.util.List;
51 |
52 | /**
53 | * Created by gqj3375 on 2017/4/28.
54 | */
55 |
56 | public class DetecterActivity extends Activity implements OnCameraListener, View.OnTouchListener, Camera.AutoFocusCallback, View.OnClickListener {
57 | private final String TAG = this.getClass().getSimpleName();
58 |
59 | private int mWidth, mHeight, mFormat;
60 | private CameraSurfaceView mSurfaceView;
61 | private CameraGLSurfaceView mGLSurfaceView;
62 | private Camera mCamera;
63 |
64 | AFT_FSDKVersion version = new AFT_FSDKVersion();
65 | AFT_FSDKEngine engine = new AFT_FSDKEngine();
66 | ASAE_FSDKVersion mAgeVersion = new ASAE_FSDKVersion();
67 | ASAE_FSDKEngine mAgeEngine = new ASAE_FSDKEngine();
68 | ASGE_FSDKVersion mGenderVersion = new ASGE_FSDKVersion();
69 | ASGE_FSDKEngine mGenderEngine = new ASGE_FSDKEngine();
70 | List result = new ArrayList<>();
71 | List ages = new ArrayList<>();
72 | List genders = new ArrayList<>();
73 |
74 | int mCameraID;
75 | int mCameraRotate;
76 | int mCameraMirror;
77 | byte[] mImageNV21 = null;
78 | FRAbsLoop mFRAbsLoop = null;
79 | AFT_FSDKFace mAFT_FSDKFace = null;
80 | Handler mHandler;
81 | boolean isPostted = false;
82 |
83 | Runnable hide = new Runnable() {
84 | @Override
85 | public void run() {
86 | mTextView.setAlpha(0.5f);
87 | mImageView.setImageAlpha(128);
88 | isPostted = false;
89 | }
90 | };
91 |
92 | class FRAbsLoop extends AbsLoop {
93 |
94 | AFR_FSDKVersion version = new AFR_FSDKVersion();
95 | AFR_FSDKEngine engine = new AFR_FSDKEngine();
96 | AFR_FSDKFace result = new AFR_FSDKFace();
97 | List mResgist = ((Application)DetecterActivity.this.getApplicationContext()).mFaceDB.mRegister;
98 | List face1 = new ArrayList<>();
99 | List face2 = new ArrayList<>();
100 |
101 | @Override
102 | public void setup() {
103 | AFR_FSDKError error = engine.AFR_FSDK_InitialEngine(FaceDB.appid, FaceDB.fr_key);
104 | Log.d(TAG, "AFR_FSDK_InitialEngine = " + error.getCode());
105 | error = engine.AFR_FSDK_GetVersion(version);
106 | Log.d(TAG, "FR=" + version.toString() + "," + error.getCode()); //(210, 178 - 478, 446), degree = 1 780, 2208 - 1942, 3370
107 | }
108 |
109 | @Override
110 | public void loop() {
111 | if (mImageNV21 != null) {
112 | final int rotate = mCameraRotate;
113 |
114 | long time = System.currentTimeMillis();
115 | AFR_FSDKError error = engine.AFR_FSDK_ExtractFRFeature(mImageNV21, mWidth, mHeight, AFR_FSDKEngine.CP_PAF_NV21, mAFT_FSDKFace.getRect(), mAFT_FSDKFace.getDegree(), result);
116 | Log.d(TAG, "AFR_FSDK_ExtractFRFeature cost :" + (System.currentTimeMillis() - time) + "ms");
117 | Log.d(TAG, "Face=" + result.getFeatureData()[0] + "," + result.getFeatureData()[1] + "," + result.getFeatureData()[2] + "," + error.getCode());
118 | AFR_FSDKMatching score = new AFR_FSDKMatching();
119 | float max = 0.0f;
120 | String name = null;
121 | for (FaceDB.FaceRegist fr : mResgist) {
122 | for (AFR_FSDKFace face : fr.mFaceList.values()) {
123 | error = engine.AFR_FSDK_FacePairMatching(result, face, score);
124 | Log.d(TAG, "Score:" + score.getScore() + ", AFR_FSDK_FacePairMatching=" + error.getCode());
125 | if (max < score.getScore()) {
126 | max = score.getScore();
127 | name = fr.mName;
128 | }
129 | }
130 | }
131 |
132 | //age & gender
133 | face1.clear();
134 | face2.clear();
135 | face1.add(new ASAE_FSDKFace(mAFT_FSDKFace.getRect(), mAFT_FSDKFace.getDegree()));
136 | face2.add(new ASGE_FSDKFace(mAFT_FSDKFace.getRect(), mAFT_FSDKFace.getDegree()));
137 | ASAE_FSDKError error1 = mAgeEngine.ASAE_FSDK_AgeEstimation_Image(mImageNV21, mWidth, mHeight, AFT_FSDKEngine.CP_PAF_NV21, face1, ages);
138 | ASGE_FSDKError error2 = mGenderEngine.ASGE_FSDK_GenderEstimation_Image(mImageNV21, mWidth, mHeight, AFT_FSDKEngine.CP_PAF_NV21, face2, genders);
139 | Log.d(TAG, "ASAE_FSDK_AgeEstimation_Image:" + error1.getCode() + ",ASGE_FSDK_GenderEstimation_Image:" + error2.getCode());
140 | Log.d(TAG, "age:" + ages.get(0).getAge() + ",gender:" + genders.get(0).getGender());
141 | final String age = ages.get(0).getAge() == 0 ? "年龄未知" : ages.get(0).getAge() + "岁";
142 | final String gender = genders.get(0).getGender() == -1 ? "性别未知" : (genders.get(0).getGender() == 0 ? "男" : "女");
143 |
144 | //crop
145 | byte[] data = mImageNV21;
146 | YuvImage yuv = new YuvImage(data, ImageFormat.NV21, mWidth, mHeight, null);
147 | ExtByteArrayOutputStream ops = new ExtByteArrayOutputStream();
148 | yuv.compressToJpeg(mAFT_FSDKFace.getRect(), 80, ops);
149 | final Bitmap bmp = BitmapFactory.decodeByteArray(ops.getByteArray(), 0, ops.getByteArray().length);
150 | try {
151 | ops.close();
152 | } catch (IOException e) {
153 | e.printStackTrace();
154 | }
155 |
156 | if (max > 0.6f) {
157 | //fr success.
158 | final float max_score = max;
159 | Log.d(TAG, "fit Score:" + max + ", NAME:" + name);
160 | final String mNameShow = name;
161 | mHandler.removeCallbacks(hide);
162 | mHandler.post(new Runnable() {
163 | @Override
164 | public void run() {
165 | mTextView.setAlpha(1.0f);
166 | mTextView.setText(mNameShow);
167 | mTextView.setTextColor(Color.RED);
168 | mTextView1.setVisibility(View.VISIBLE);
169 | mTextView1.setText("置信度:" + (float)((int)(max_score * 1000)) / 1000.0);
170 | mTextView1.setTextColor(Color.RED);
171 | mImageView.setRotation(rotate);
172 | mImageView.setScaleY(-mCameraMirror);
173 | mImageView.setImageAlpha(255);
174 | mImageView.setImageBitmap(bmp);
175 | }
176 | });
177 | } else {
178 | final String mNameShow = "未识别";
179 | DetecterActivity.this.runOnUiThread(new Runnable() {
180 | @Override
181 | public void run() {
182 | mTextView.setAlpha(1.0f);
183 | mTextView1.setVisibility(View.VISIBLE);
184 | mTextView1.setText( gender + "," + age);
185 | mTextView1.setTextColor(Color.RED);
186 | mTextView.setText(mNameShow);
187 | mTextView.setTextColor(Color.RED);
188 | mImageView.setImageAlpha(255);
189 | mImageView.setRotation(rotate);
190 | mImageView.setScaleY(-mCameraMirror);
191 | mImageView.setImageBitmap(bmp);
192 | }
193 | });
194 | }
195 | mImageNV21 = null;
196 | }
197 |
198 | }
199 |
200 | @Override
201 | public void over() {
202 | AFR_FSDKError error = engine.AFR_FSDK_UninitialEngine();
203 | Log.d(TAG, "AFR_FSDK_UninitialEngine : " + error.getCode());
204 | }
205 | }
206 |
207 | private TextView mTextView;
208 | private TextView mTextView1;
209 | private ImageView mImageView;
210 | private ImageButton mImageButton;
211 |
212 | /* (non-Javadoc)
213 | * @see android.app.Activity#onCreate(android.os.Bundle)
214 | */
215 | @Override
216 | protected void onCreate(Bundle savedInstanceState) {
217 | // TODO Auto-generated method stub
218 | super.onCreate(savedInstanceState);
219 |
220 | mCameraID = getIntent().getIntExtra("Camera", 0) == 0 ? Camera.CameraInfo.CAMERA_FACING_BACK : Camera.CameraInfo.CAMERA_FACING_FRONT;
221 | mCameraRotate = getIntent().getIntExtra("Camera", 0) == 0 ? 90 : 270;
222 | mCameraMirror = getIntent().getIntExtra("Camera", 0) == 0 ? GLES2Render.MIRROR_NONE : GLES2Render.MIRROR_X;
223 | mWidth = 1280;
224 | mHeight = 960;
225 | mFormat = ImageFormat.NV21;
226 | mHandler = new Handler();
227 |
228 | setContentView(R.layout.activity_camera);
229 | mGLSurfaceView = (CameraGLSurfaceView) findViewById(R.id.glsurfaceView);
230 | mGLSurfaceView.setOnTouchListener(this);
231 | mSurfaceView = (CameraSurfaceView) findViewById(R.id.surfaceView);
232 | mSurfaceView.setOnCameraListener(this);
233 | mSurfaceView.setupGLSurafceView(mGLSurfaceView, true, mCameraMirror, mCameraRotate);
234 | mSurfaceView.debug_print_fps(true, false);
235 |
236 | //snap
237 | mTextView = (TextView) findViewById(R.id.textView);
238 | mTextView.setText("");
239 | mTextView1 = (TextView) findViewById(R.id.textView1);
240 | mTextView1.setText("");
241 |
242 | mImageView = (ImageView) findViewById(R.id.imageView);
243 | mImageButton = (ImageButton) findViewById(R.id.imageButton);
244 | mImageButton.setOnClickListener(this);
245 |
246 | AFT_FSDKError err = engine.AFT_FSDK_InitialFaceEngine(FaceDB.appid, FaceDB.ft_key, AFT_FSDKEngine.AFT_OPF_0_HIGHER_EXT, 16, 5);
247 | Log.d(TAG, "AFT_FSDK_InitialFaceEngine =" + err.getCode());
248 | err = engine.AFT_FSDK_GetVersion(version);
249 | Log.d(TAG, "AFT_FSDK_GetVersion:" + version.toString() + "," + err.getCode());
250 |
251 | ASAE_FSDKError error = mAgeEngine.ASAE_FSDK_InitAgeEngine(FaceDB.appid, FaceDB.age_key);
252 | Log.d(TAG, "ASAE_FSDK_InitAgeEngine =" + error.getCode());
253 | error = mAgeEngine.ASAE_FSDK_GetVersion(mAgeVersion);
254 | Log.d(TAG, "ASAE_FSDK_GetVersion:" + mAgeVersion.toString() + "," + error.getCode());
255 |
256 | ASGE_FSDKError error1 = mGenderEngine.ASGE_FSDK_InitgGenderEngine(FaceDB.appid, FaceDB.gender_key);
257 | Log.d(TAG, "ASGE_FSDK_InitgGenderEngine =" + error1.getCode());
258 | error1 = mGenderEngine.ASGE_FSDK_GetVersion(mGenderVersion);
259 | Log.d(TAG, "ASGE_FSDK_GetVersion:" + mGenderVersion.toString() + "," + error1.getCode());
260 |
261 | mFRAbsLoop = new FRAbsLoop();
262 | mFRAbsLoop.start();
263 | }
264 |
265 | /* (non-Javadoc)
266 | * @see android.app.Activity#onDestroy()
267 | */
268 | @Override
269 | protected void onDestroy() {
270 | // TODO Auto-generated method stub
271 | super.onDestroy();
272 | mFRAbsLoop.shutdown();
273 | AFT_FSDKError err = engine.AFT_FSDK_UninitialFaceEngine();
274 | Log.d(TAG, "AFT_FSDK_UninitialFaceEngine =" + err.getCode());
275 |
276 | ASAE_FSDKError err1 = mAgeEngine.ASAE_FSDK_UninitAgeEngine();
277 | Log.d(TAG, "ASAE_FSDK_UninitAgeEngine =" + err1.getCode());
278 |
279 | ASGE_FSDKError err2 = mGenderEngine.ASGE_FSDK_UninitGenderEngine();
280 | Log.d(TAG, "ASGE_FSDK_UninitGenderEngine =" + err2.getCode());
281 | }
282 |
283 | @Override
284 | public Camera setupCamera() {
285 | // TODO Auto-generated method stub
286 | mCamera = Camera.open(mCameraID);
287 | try {
288 | Camera.Parameters parameters = mCamera.getParameters();
289 | parameters.setPreviewSize(mWidth, mHeight);
290 | parameters.setPreviewFormat(mFormat);
291 |
292 | for( Camera.Size size : parameters.getSupportedPreviewSizes()) {
293 | Log.d(TAG, "SIZE:" + size.width + "x" + size.height);
294 | }
295 | for( Integer format : parameters.getSupportedPreviewFormats()) {
296 | Log.d(TAG, "FORMAT:" + format);
297 | }
298 |
299 | List fps = parameters.getSupportedPreviewFpsRange();
300 | for(int[] count : fps) {
301 | Log.d(TAG, "T:");
302 | for (int data : count) {
303 | Log.d(TAG, "V=" + data);
304 | }
305 | }
306 | //parameters.setPreviewFpsRange(15000, 30000);
307 | //parameters.setExposureCompensation(parameters.getMaxExposureCompensation());
308 | //parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
309 | //parameters.setAntibanding(Camera.Parameters.ANTIBANDING_AUTO);
310 | //parmeters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
311 | //parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
312 | //parameters.setColorEffect(Camera.Parameters.EFFECT_NONE);
313 | mCamera.setParameters(parameters);
314 | } catch (Exception e) {
315 | e.printStackTrace();
316 | }
317 | if (mCamera != null) {
318 | mWidth = mCamera.getParameters().getPreviewSize().width;
319 | mHeight = mCamera.getParameters().getPreviewSize().height;
320 | }
321 | return mCamera;
322 | }
323 |
324 | @Override
325 | public void setupChanged(int format, int width, int height) {
326 |
327 | }
328 |
329 | @Override
330 | public boolean startPreviewImmediately() {
331 | return true;
332 | }
333 |
334 | @Override
335 | public Object onPreview(byte[] data, int width, int height, int format, long timestamp) {
336 | AFT_FSDKError err = engine.AFT_FSDK_FaceFeatureDetect(data, width, height, AFT_FSDKEngine.CP_PAF_NV21, result);
337 | Log.d(TAG, "AFT_FSDK_FaceFeatureDetect =" + err.getCode());
338 | Log.d(TAG, "Face=" + result.size());
339 | for (AFT_FSDKFace face : result) {
340 | Log.d(TAG, "Face:" + face.toString());
341 | }
342 | if (mImageNV21 == null) {
343 | if (!result.isEmpty()) {
344 | mAFT_FSDKFace = result.get(0).clone();
345 | mImageNV21 = data.clone();
346 | } else {
347 | if (!isPostted) {
348 | mHandler.removeCallbacks(hide);
349 | mHandler.postDelayed(hide, 2000);
350 | isPostted = true;
351 | }
352 | }
353 | }
354 | //copy rects
355 | Rect[] rects = new Rect[result.size()];
356 | for (int i = 0; i < result.size(); i++) {
357 | rects[i] = new Rect(result.get(i).getRect());
358 | }
359 | //clear result.
360 | result.clear();
361 | //return the rects for render.
362 | return rects;
363 | }
364 |
365 | @Override
366 | public void onBeforeRender(CameraFrameData data) {
367 |
368 | }
369 |
370 | @Override
371 | public void onAfterRender(CameraFrameData data) {
372 | mGLSurfaceView.getGLES2Render().draw_rect((Rect[])data.getParams(), Color.GREEN, 2);
373 | }
374 |
375 | @Override
376 | public boolean onTouch(View v, MotionEvent event) {
377 | CameraHelper.touchFocus(mCamera, event, v, this);
378 | return false;
379 | }
380 |
381 | @Override
382 | public void onAutoFocus(boolean success, Camera camera) {
383 | if (success) {
384 | Log.d(TAG, "Camera Focus SUCCESS!");
385 | }
386 | }
387 |
388 | @Override
389 | public void onClick(View view) {
390 | if (view.getId() == R.id.imageButton) {
391 | if (mCameraID == Camera.CameraInfo.CAMERA_FACING_BACK) {
392 | mCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
393 | mCameraRotate = 270;
394 | mCameraMirror = GLES2Render.MIRROR_X;
395 | } else {
396 | mCameraID = Camera.CameraInfo.CAMERA_FACING_BACK;
397 | mCameraRotate = 90;
398 | mCameraMirror = GLES2Render.MIRROR_NONE;
399 | }
400 | mSurfaceView.resetCamera();
401 | mGLSurfaceView.setRenderConfig(mCameraRotate, mCameraMirror);
402 | mGLSurfaceView.getGLES2Render().setViewDisplay(mCameraMirror, mCameraRotate);
403 | }
404 | }
405 |
406 | }
407 |
--------------------------------------------------------------------------------
/ArcFaceDemo-master/src/main/java/com/arcsoft/sdk_demo/RegisterActivity.java:
--------------------------------------------------------------------------------
1 | package com.arcsoft.sdk_demo;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.database.DataSetObserver;
8 | import android.graphics.Bitmap;
9 | import android.graphics.BitmapFactory;
10 | import android.graphics.Canvas;
11 | import android.graphics.Color;
12 | import android.graphics.Paint;
13 | import android.graphics.Rect;
14 | import android.os.Bundle;
15 | import android.os.Message;
16 | import android.text.InputFilter;
17 | import android.util.Log;
18 | import android.view.LayoutInflater;
19 | import android.view.SurfaceHolder;
20 | import android.view.SurfaceView;
21 | import android.view.View;
22 | import android.view.ViewGroup;
23 | import android.widget.AdapterView;
24 | import android.widget.BaseAdapter;
25 | import android.widget.EditText;
26 | import android.widget.ImageView;
27 | import android.widget.ListAdapter;
28 | import android.widget.ListView;
29 | import android.widget.TextView;
30 | import android.widget.Toast;
31 |
32 | import com.arcsoft.facedetection.AFD_FSDKEngine;
33 | import com.arcsoft.facedetection.AFD_FSDKError;
34 | import com.arcsoft.facedetection.AFD_FSDKFace;
35 | import com.arcsoft.facedetection.AFD_FSDKVersion;
36 | import com.arcsoft.facerecognition.AFR_FSDKEngine;
37 | import com.arcsoft.facerecognition.AFR_FSDKError;
38 | import com.arcsoft.facerecognition.AFR_FSDKFace;
39 | import com.arcsoft.facerecognition.AFR_FSDKVersion;
40 | import com.guo.android_extend.image.ImageConverter;
41 | import com.guo.android_extend.widget.ExtImageView;
42 | import com.guo.android_extend.widget.HListView;
43 | import com.guo.android_extend.widget.controller.ImageController;
44 |
45 | import java.util.ArrayList;
46 | import java.util.List;
47 | import java.util.Map;
48 |
49 | /**
50 | * Created by gqj3375 on 2017/4/27.
51 | */
52 |
53 | public class RegisterActivity extends Activity implements SurfaceHolder.Callback {
54 | private final String TAG = this.getClass().toString();
55 | private final static int MSG_CODE = 0x1000;
56 | private final static int MSG_EVENT_REG = 0x1001;
57 | private final static int MSG_EVENT_NO_FACE = 0x1002;
58 | private final static int MSG_EVENT_NO_FEATURE = 0x1003;
59 | private final static int MSG_EVENT_FD_ERROR = 0x1004;
60 | private final static int MSG_EVENT_FR_ERROR = 0x1005;
61 | private final static int MSG_EVENT_IMG_ERROR = 0x1006;
62 | private UIHandler mUIHandler;
63 | // Intent data.
64 | private String mFilePath;
65 |
66 | private SurfaceView mSurfaceView;
67 | private SurfaceHolder mSurfaceHolder;
68 | private Bitmap mBitmap;
69 | private Rect src = new Rect();
70 | private Rect dst = new Rect();
71 | private Thread view;
72 | private EditText mEditText;
73 | private ExtImageView mExtImageView;
74 | private HListView mHListView;
75 | private RegisterViewAdapter mRegisterViewAdapter;
76 | private AFR_FSDKFace mAFR_FSDKFace;
77 |
78 | @Override
79 | protected void onCreate(Bundle savedInstanceState) {
80 | // TODO Auto-generated method stub
81 | super.onCreate(savedInstanceState);
82 | this.setContentView(R.layout.activity_register);
83 | //initial data.
84 | if (!getIntentData(getIntent().getExtras())) {
85 | Log.e(TAG, "getIntentData fail!");
86 | this.finish() ;
87 | }
88 |
89 | mRegisterViewAdapter = new RegisterViewAdapter(this);
90 | mHListView = (HListView)findViewById(R.id.hlistView);
91 | mHListView.setAdapter(mRegisterViewAdapter);
92 | mHListView.setOnItemClickListener(mRegisterViewAdapter);
93 |
94 | mUIHandler = new UIHandler();
95 | mBitmap = Application.decodeImage(mFilePath);
96 | src.set(0,0,mBitmap.getWidth(),mBitmap.getHeight());
97 | mSurfaceView = (SurfaceView)this.findViewById(R.id.surfaceView);
98 | mSurfaceView.getHolder().addCallback(this);
99 | view = new Thread(new Runnable() {
100 | @Override
101 | public void run() {
102 | while (mSurfaceHolder == null) {
103 | try {
104 | Thread.sleep(100);
105 | } catch (InterruptedException e) {
106 | e.printStackTrace();
107 | }
108 | }
109 |
110 | byte[] data = new byte[mBitmap.getWidth() * mBitmap.getHeight() * 3 / 2];
111 | try {
112 | ImageConverter convert = new ImageConverter();
113 | convert.initial(mBitmap.getWidth(), mBitmap.getHeight(), ImageConverter.CP_PAF_NV21);
114 | if (convert.convert(mBitmap, data)) {
115 | Log.d(TAG, "convert ok!");
116 | }
117 | convert.destroy();
118 | } catch (Exception e) {
119 | e.printStackTrace();
120 | Message reg = Message.obtain();
121 | reg.what = MSG_CODE;
122 | reg.arg1 = MSG_EVENT_IMG_ERROR;
123 | reg.obj = e.getMessage();
124 | mUIHandler.sendMessage(reg);
125 | }
126 |
127 | AFD_FSDKEngine engine = new AFD_FSDKEngine();
128 | AFD_FSDKVersion version = new AFD_FSDKVersion();
129 | List result = new ArrayList();
130 | AFD_FSDKError err = engine.AFD_FSDK_InitialFaceEngine(FaceDB.appid, FaceDB.fd_key, AFD_FSDKEngine.AFD_OPF_0_HIGHER_EXT, 16, 5);
131 | Log.d(TAG, "AFD_FSDK_InitialFaceEngine = " + err.getCode());
132 | if (err.getCode() != AFD_FSDKError.MOK) {
133 | Message reg = Message.obtain();
134 | reg.what = MSG_CODE;
135 | reg.arg1 = MSG_EVENT_FD_ERROR;
136 | reg.arg2 = err.getCode();
137 | mUIHandler.sendMessage(reg);
138 | }
139 | err = engine.AFD_FSDK_GetVersion(version);
140 | Log.d(TAG, "AFD_FSDK_GetVersion =" + version.toString() + ", " + err.getCode());
141 | err = engine.AFD_FSDK_StillImageFaceDetection(data, mBitmap.getWidth(), mBitmap.getHeight(), AFD_FSDKEngine.CP_PAF_NV21, result);
142 | Log.d(TAG, "AFD_FSDK_StillImageFaceDetection =" + err.getCode() + "<" + result.size());
143 | while (mSurfaceHolder != null) {
144 | Canvas canvas = mSurfaceHolder.lockCanvas();
145 | if (canvas != null) {
146 | Paint mPaint = new Paint();
147 | boolean fit_horizontal = canvas.getWidth() / (float)src.width() < canvas.getHeight() / (float)src.height() ? true : false;
148 | float scale = 1.0f;
149 | if (fit_horizontal) {
150 | scale = canvas.getWidth() / (float)src.width();
151 | dst.left = 0;
152 | dst.top = (canvas.getHeight() - (int)(src.height() * scale)) / 2;
153 | dst.right = dst.left + canvas.getWidth();
154 | dst.bottom = dst.top + (int)(src.height() * scale);
155 | } else {
156 | scale = canvas.getHeight() / (float)src.height();
157 | dst.left = (canvas.getWidth() - (int)(src.width() * scale)) / 2;
158 | dst.top = 0;
159 | dst.right = dst.left + (int)(src.width() * scale);
160 | dst.bottom = dst.top + canvas.getHeight();
161 | }
162 | canvas.drawBitmap(mBitmap, src, dst, mPaint);
163 | canvas.save();
164 | canvas.scale((float) dst.width() / (float) src.width(), (float) dst.height() / (float) src.height());
165 | canvas.translate(dst.left / scale, dst.top / scale);
166 | for (AFD_FSDKFace face : result) {
167 | mPaint.setColor(Color.RED);
168 | mPaint.setStrokeWidth(10.0f);
169 | mPaint.setStyle(Paint.Style.STROKE);
170 | canvas.drawRect(face.getRect(), mPaint);
171 | }
172 | canvas.restore();
173 | mSurfaceHolder.unlockCanvasAndPost(canvas);
174 | break;
175 | }
176 | }
177 |
178 | if (!result.isEmpty()) {
179 | AFR_FSDKVersion version1 = new AFR_FSDKVersion();
180 | AFR_FSDKEngine engine1 = new AFR_FSDKEngine();
181 | AFR_FSDKFace result1 = new AFR_FSDKFace();
182 | AFR_FSDKError error1 = engine1.AFR_FSDK_InitialEngine(FaceDB.appid, FaceDB.fr_key);
183 | Log.d("com.arcsoft", "AFR_FSDK_InitialEngine = " + error1.getCode());
184 | if (error1.getCode() != AFD_FSDKError.MOK) {
185 | Message reg = Message.obtain();
186 | reg.what = MSG_CODE;
187 | reg.arg1 = MSG_EVENT_FR_ERROR;
188 | reg.arg2 = error1.getCode();
189 | mUIHandler.sendMessage(reg);
190 | }
191 | error1 = engine1.AFR_FSDK_GetVersion(version1);
192 | Log.d("com.arcsoft", "FR=" + version.toString() + "," + error1.getCode()); //(210, 178 - 478, 446), degree = 1 780, 2208 - 1942, 3370
193 | error1 = engine1.AFR_FSDK_ExtractFRFeature(data, mBitmap.getWidth(), mBitmap.getHeight(), AFR_FSDKEngine.CP_PAF_NV21, new Rect(result.get(0).getRect()), result.get(0).getDegree(), result1);
194 | Log.d("com.arcsoft", "Face=" + result1.getFeatureData()[0] + "," + result1.getFeatureData()[1] + "," + result1.getFeatureData()[2] + "," + error1.getCode());
195 | if(error1.getCode() == error1.MOK) {
196 | mAFR_FSDKFace = result1.clone();
197 | int width = result.get(0).getRect().width();
198 | int height = result.get(0).getRect().height();
199 | Bitmap face_bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
200 | Canvas face_canvas = new Canvas(face_bitmap);
201 | face_canvas.drawBitmap(mBitmap, result.get(0).getRect(), new Rect(0, 0, width, height), null);
202 | Message reg = Message.obtain();
203 | reg.what = MSG_CODE;
204 | reg.arg1 = MSG_EVENT_REG;
205 | reg.obj = face_bitmap;
206 | mUIHandler.sendMessage(reg);
207 | } else {
208 | Message reg = Message.obtain();
209 | reg.what = MSG_CODE;
210 | reg.arg1 = MSG_EVENT_NO_FEATURE;
211 | mUIHandler.sendMessage(reg);
212 | }
213 | error1 = engine1.AFR_FSDK_UninitialEngine();
214 | Log.d("com.arcsoft", "AFR_FSDK_UninitialEngine : " + error1.getCode());
215 | } else {
216 | Message reg = Message.obtain();
217 | reg.what = MSG_CODE;
218 | reg.arg1 = MSG_EVENT_NO_FACE;
219 | mUIHandler.sendMessage(reg);
220 | }
221 | err = engine.AFD_FSDK_UninitialFaceEngine();
222 | Log.d(TAG, "AFD_FSDK_UninitialFaceEngine =" + err.getCode());
223 | }
224 | });
225 | view.start();
226 |
227 | }
228 |
229 | /**
230 | * @note bundle data :
231 | * String imagePath
232 | *
233 | * @param bundle
234 | */
235 | private boolean getIntentData(Bundle bundle) {
236 | try {
237 | mFilePath = bundle.getString("imagePath");
238 | if (mFilePath == null || mFilePath.isEmpty()) {
239 | return false;
240 | }
241 | Log.i(TAG, "getIntentData:" + mFilePath);
242 | return true;
243 | } catch (Exception e) {
244 | e.printStackTrace();
245 | }
246 | return false;
247 | }
248 |
249 | @Override
250 | public void surfaceCreated(SurfaceHolder holder) {
251 | mSurfaceHolder = holder;
252 | }
253 |
254 | @Override
255 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
256 |
257 | }
258 |
259 | @Override
260 | public void surfaceDestroyed(SurfaceHolder holder) {
261 | mSurfaceHolder = null;
262 | try {
263 | view.join();
264 | } catch (InterruptedException e) {
265 | e.printStackTrace();
266 | }
267 | }
268 |
269 | class UIHandler extends android.os.Handler {
270 | @Override
271 | public void handleMessage(Message msg) {
272 | super.handleMessage(msg);
273 | if (msg.what == MSG_CODE) {
274 | if (msg.arg1 == MSG_EVENT_REG) {
275 | LayoutInflater inflater = LayoutInflater.from(RegisterActivity.this);
276 | View layout = inflater.inflate(R.layout.dialog_register, null);
277 | mEditText = (EditText) layout.findViewById(R.id.editview);
278 | mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
279 | mExtImageView = (ExtImageView) layout.findViewById(R.id.extimageview);
280 | mExtImageView.setImageBitmap((Bitmap) msg.obj);
281 | final Bitmap face = (Bitmap) msg.obj;
282 | new AlertDialog.Builder(RegisterActivity.this)
283 | .setTitle("请输入注册名字")
284 | .setIcon(android.R.drawable.ic_dialog_info)
285 | .setView(layout)
286 | .setPositiveButton("确定", new DialogInterface.OnClickListener() {
287 | @Override
288 | public void onClick(DialogInterface dialog, int which) {
289 | ((Application)RegisterActivity.this.getApplicationContext()).mFaceDB.addFace(mEditText.getText().toString(), mAFR_FSDKFace, face);
290 | mRegisterViewAdapter.notifyDataSetChanged();
291 | dialog.dismiss();
292 | }
293 | })
294 | .setNegativeButton("取消", new DialogInterface.OnClickListener() {
295 | @Override
296 | public void onClick(DialogInterface dialog, int which) {
297 | dialog.dismiss();
298 | }
299 | })
300 | .show();
301 | } else if(msg.arg1 == MSG_EVENT_NO_FEATURE ){
302 | Toast.makeText(RegisterActivity.this, "人脸特征无法检测,请换一张图片", Toast.LENGTH_SHORT).show();
303 | } else if(msg.arg1 == MSG_EVENT_NO_FACE ){
304 | Toast.makeText(RegisterActivity.this, "没有检测到人脸,请换一张图片", Toast.LENGTH_SHORT).show();
305 | } else if(msg.arg1 == MSG_EVENT_FD_ERROR ){
306 | Toast.makeText(RegisterActivity.this, "FD初始化失败,错误码:" + msg.arg2, Toast.LENGTH_SHORT).show();
307 | } else if(msg.arg1 == MSG_EVENT_FR_ERROR){
308 | Toast.makeText(RegisterActivity.this, "FR初始化失败,错误码:" + msg.arg2, Toast.LENGTH_SHORT).show();
309 | } else if(msg.arg1 == MSG_EVENT_IMG_ERROR){
310 | Toast.makeText(RegisterActivity.this, "图像格式错误,:" + msg.obj, Toast.LENGTH_SHORT).show();
311 | }
312 | }
313 | }
314 | }
315 |
316 | class Holder {
317 | ExtImageView siv;
318 | TextView tv;
319 | }
320 |
321 | class RegisterViewAdapter extends BaseAdapter implements AdapterView.OnItemClickListener{
322 | Context mContext;
323 | LayoutInflater mLInflater;
324 |
325 | public RegisterViewAdapter(Context c) {
326 | // TODO Auto-generated constructor stub
327 | mContext = c;
328 | mLInflater = LayoutInflater.from(mContext);
329 | }
330 |
331 | @Override
332 | public int getCount() {
333 | // TODO Auto-generated method stub
334 | return ((Application)mContext.getApplicationContext()).mFaceDB.mRegister.size();
335 | }
336 |
337 | @Override
338 | public Object getItem(int arg0) {
339 | // TODO Auto-generated method stub
340 | return null;
341 | }
342 |
343 | @Override
344 | public long getItemId(int position) {
345 | // TODO Auto-generated method stub
346 | return position;
347 | }
348 |
349 | @Override
350 | public View getView(int position, View convertView, ViewGroup parent) {
351 | // TODO Auto-generated method stub
352 | Holder holder = null;
353 | if (convertView != null) {
354 | holder = (Holder) convertView.getTag();
355 | } else {
356 | convertView = mLInflater.inflate(R.layout.item_sample, null);
357 | holder = new Holder();
358 | holder.siv = (ExtImageView) convertView.findViewById(R.id.imageView1);
359 | holder.tv = (TextView) convertView.findViewById(R.id.textView1);
360 | convertView.setTag(holder);
361 | }
362 |
363 | if (!((Application)mContext.getApplicationContext()).mFaceDB.mRegister.isEmpty()) {
364 | FaceDB.FaceRegist face = ((Application) mContext.getApplicationContext()).mFaceDB.mRegister.get(position);
365 | holder.tv.setText(face.mName);
366 | String keyPath = face.mFaceList.keySet().iterator().next();
367 | holder.siv.setImageBitmap(BitmapFactory.decodeFile(keyPath));
368 | holder.siv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
369 | //holder.siv.setImageResource(R.mipmap.ic_launcher);
370 | convertView.setWillNotDraw(false);
371 | }
372 |
373 | return convertView;
374 | }
375 |
376 | @Override
377 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
378 | Log.d("onItemClick", "onItemClick = " + position + "pos=" + mHListView.getScroll());
379 | final String name = ((Application)mContext.getApplicationContext()).mFaceDB.mRegister.get(position).mName;
380 | final int count = ((Application)mContext.getApplicationContext()).mFaceDB.mRegister.get(position).mFaceList.size();
381 | final Map face = ((Application)mContext.getApplicationContext()).mFaceDB.mRegister.get(position).mFaceList;
382 | new AlertDialog.Builder(RegisterActivity.this)
383 | .setTitle("删除注册名:" + name)
384 | .setMessage("包含:" + count + "个注册人脸特征信息")
385 | .setView(new ListView(mContext))
386 | .setIcon(android.R.drawable.ic_dialog_alert)
387 | .setPositiveButton("确定", new DialogInterface.OnClickListener() {
388 | @Override
389 | public void onClick(DialogInterface dialog, int which) {
390 | ((Application)mContext.getApplicationContext()).mFaceDB.delete(name);
391 | mRegisterViewAdapter.notifyDataSetChanged();
392 | dialog.dismiss();
393 | }
394 | })
395 | .setNegativeButton("取消", new DialogInterface.OnClickListener() {
396 | @Override
397 | public void onClick(DialogInterface dialog, int which) {
398 | dialog.dismiss();
399 | }
400 | })
401 | .show();
402 | }
403 | }
404 | }
405 |
--------------------------------------------------------------------------------