[Huawei Developers] Basavaraj.navi:
Introduction

In this article, we will learn how to compare two faces for entertainment. And check how much similar or the same person or another person. Many times most of the people says that you looks like X hero, heroine or singer etc. Now it’s time to check how much percentage you are similar with celebraty.

Facial comparison recognizes and extracts key facial features, performs high-precision comparisons of human faces, provides confidence scores, and determines whether the same person appears across different images. Cutting-edge facial comparison technology intelligently categorizes and manages photos. An intelligent image recognition algorithm ensures accurate facial recognition, and enables apps to provide an enhanced user experience.

It is not recommended that this algorithm be used for identity authentication (such as phone unlocking and secure payment). It can be applied in in-app scenarios where face similarity comparison is required, for example: to compare the similarity between two faces, or the similarity between a person and a celebrity in an entertainment app.

For two photos of one person, the result will show that the same person is appearing in both photos, and the confidence score will be high. For photos of two different persons, the result will show that the two photos are not of the same person, and the confidence score will be low.

How to integrate Facial Comparison

1. Configure the application on the AGC.

2. Apply for HiAI Engine Library.

3. Client application development process.

Configure application on the AGC

Follow the steps

Step 1: We need to register as a developer account in AppGallery Connect. If you are already a developer ignore this step.

Step 2: Create an app by referring to Creating a Project and Creating an App in the Project

Step 3: Set the data storage location based on the current location.

Step 4: Generating a Signing Certificate Fingerprint.

Step 5: Configuring the Signing Certificate Fingerprint.

Step 6: Download your agconnect-services.json file, paste it into the app root directory.

Apply for HiAI Engine Library

What is Huawei HiAI?

HiAI is Huawei’s AI computing platform. HUAWEI HiAI is a mobile terminal–oriented artificial intelligence (AI) computing platform that constructs three layers of ecology: service capability openness, application capability openness, and chip capability openness. The three-layer open platform that integrates terminals, chips, and the cloud brings more extraordinary experience for users and developers.

How to apply for HiAI Engine?

Follow the steps

Step 1: Navigate to this URL, choose App Service > Development and click HUAWEI HiAI.

Step 2: Click Apply for HUAWEI HiAI kit.

Step 3: Enter required information like Product name and Package name, click Next button.

Step 4: Verify the application details and click Submit button.

Step 5: Click the Download SDK button to open the SDK list.

Step 6: Unzip downloaded SDK and add into your android project under libs folder.

Step 7: Add jar files dependences into app build.gradle file.

implementation fileTree(include: ['*.aar', '*.jar'], dir: 'libs')
implementation 'com.google.code.gson:gson:2.8.6'
repositories {
flatDir {
dirs 'libs'
}
}

Client application development process

Follow the steps.

Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).

Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.

apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'

Root level gradle dependencies.

maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'

Step 3: Add permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Step 4: Build application.

Request the runtime permission.

private void requestPermissions() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permission = ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 0x0010);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}Copy codeCopy code

public void onClickButton(View view) {
int requestCode;
switch (view.getId()) {
case R.id.btnPerson1: {
Log.d(TAG, "btnPerson1");
isPerson1 = true;
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
requestCode = PHOTO_REQUEST_GALLERY;
startActivityForResult(intent, requestCode);
break;
}
case R.id.btnPerson2: {
Log.d(TAG, "btnPerson2");
isPerson1 = false;
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
requestCode = PHOTO_REQUEST_GALLERY;
startActivityForResult(intent, requestCode);
break;
}
case R.id.btnstarCompare: {
startCompare();
break;
}
default:
break;
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
Uri selectedImage = data.getData();
int type = data.getIntExtra("type", TYPE_CHOOSE_PHOTO_CODE4PERSON1);
Log.d(TAG, "select uri:" + selectedImage.toString() + "type: " + type);
mTxtViewResult.setText("");
getBitmap(type, selectedImage);
}
}

private void getBitmap(int type, Uri imageUri) {
String[] pathColumn = {MediaStore.Images.Media.DATA};

Cursor cursor = getContentResolver().query(imageUri, pathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(pathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();

if (isPerson1) {
mBitmapPerson1 = BitmapFactory.decodeFile(picturePath);
mHander.sendEmptyMessage(TYPE_CHOOSE_PHOTO_CODE4PERSON1);
} else {
mBitmapPerson2 = BitmapFactory.decodeFile(picturePath);
mHander.sendEmptyMessage(TYPE_CHOOSE_PHOTO_CODE4PERSON2);
}
}

@SuppressLint("HandlerLeak")
private Handler mHander = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int status = msg.what;
Log.d(TAG, "handleMessage status = " + status);
switch (status) {
case TYPE_CHOOSE_PHOTO_CODE4PERSON1: {
if (mBitmapPerson1 == null) {
Log.e(TAG, "bitmap person1 is null !!!! ");
return;
}
mImageViewPerson1.setImageBitmap(mBitmapPerson1);
break;
}
case TYPE_CHOOSE_PHOTO_CODE4PERSON2: {
if (mBitmapPerson2 == null) {
Log.e(TAG, "bitmap person2 is null !!!! ");
return;
}
mImageViewPerson2.setImageBitmap(mBitmapPerson2);
break;
}
case TYPE_SHOW_RESULE: {
FaceCompareResult result = (FaceCompareResult) msg.obj;
if (result == null) {
mTxtViewResult.setText("Not the same person, result is null");
break;
}

if (result.isSamePerson()) {
mTxtViewResult.setText("The same Person, and score: " + result.getSocre());
} else {
mTxtViewResult.setText("Not the same Person, and score:" + result.getSocre());
}
break;
}
default:
break;
}
}
};

private void startCompare() {
mTxtViewResult.setText("Is the same Person ?");
synchronized (mWaitResult) {
mWaitResult.notifyAll();
}
}

private Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
mFaceComparator = new FaceComparator(getApplicationContext());
FaceComparator faceComparator = mFaceComparator;
while (true) {
try {
synchronized (mWaitResult) {
mWaitResult.wait();
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
}

Log.d(TAG, "start Compare !!!! ");
Frame frame1 = new Frame();
frame1.setBitmap(mBitmapPerson1);
Frame frame2 = new Frame();
frame2.setBitmap(mBitmapPerson2);

JSONObject jsonObject = faceComparator.faceCompare(frame1, frame2, null);
if (jsonObject != null)
Log.d(TAG, "Compare end !!!! json: " + jsonObject.toString());
FaceCompareResult result = faceComparator.convertResult(jsonObject);
Log.d(TAG, "convertResult end !!!! ");

Message msg = new Message();
msg.what = TYPE_SHOW_RESULE;
msg.obj = result;
mHander.sendMessage(msg);
}
}
});

Result

Same person different photos.

Different persons different photos

Tips and Tricks

An error code is returned, if the size of an image exceeds 20 MP.

Multi-thread invoking is currently not supported.

Intra-process and inter-process support.

This API can be called only by 64-bit apps.

If you are taking Video from a camera or gallery make sure your app has camera and storage permissions.

Add the downloaded huawei-hiai-vision-ove-10.0.4.307.aar, huawei-hiai-pdk-1.0.0.aar file to libs folder.

Check dependencies added properly.

Latest HMS Core APK is required.

Min SDK is 21. Otherwise you will get Manifest merge issue.

Conclusion

In this article, we have learnt what the facial comparison is and how to integrate facial comparison using Huawei HiAI using android with java. We got the result between same person different photos and different person different photos.

Reference

Facial Comparison

Apply for Huawei HiAI