Xây dựng ứng dụng Phát hiện khuôn mặt – Lập trình ứng dụng Android

 Link tham khảo API phát hiện khuôn mặt: https://developers.google.com/ml-kit/vision/face-detection

Với API phát hiện khuôn mặt của ML Kit được phát triển bởi Google, bạn có thể phát hiện khuôn mặt trong một hình ảnh, xác định các đặc điểm chính trên khuôn mặt và có được các đường viền của khuôn mặt được phát hiện. API này chỉ phát hiện khuôn mặt chứ không nhận dạng khuôn mặt người .

Vì ML Kit có thể phát hiện khuôn mặt theo thời gian thực, nên bạn có thể sử dụng bộ công cụ này trong các ứng dụng Video.

Các bạn thực hiện theo các bước sau để xây dựng ứng dụng Phát hiện khuôn mặt:

Bước 1: Trong tệp build.gradle ở cấp Project, hãy nhớ đưa kho lưu trữ Maven của Google vào cả hai phần buildscript và allprojects. (Thông thường, khi bạn tạo một ứng dụng đều đã tích hợp phần này, nên có thể bỏ qua bước này).

Bước 2: Thêm thư viện phát hiện khuôn mặt vào tệp  app/build.gradle cấp ứng dụng:

dependencies {
// Use this dependency to bundle the model with your app
implementation 'com.google.mlkit:face-detection:16.1.7'
}

Thêm khai báo sau vào tệp AndroidManifest.xml:

<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="face" />
<!-- To use multiple models: android:value="face,model2,model3" -->

Bước 3: Xây dựng giao diện trong tệp activity_main.xml”:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:orientation="vertical"
android:gravity="center"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_weight="1"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:id="@+id/img_1" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_weight="1"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:layout_marginTop="20dp"
android:id="@+id/img_2" />
</LinearLayout>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Chọn ảnh"
app:layout_constraintBottom_toBottomOf="parent"
android:id="@+id/btn_chonanh"
android:layout_margin="5dp"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

Bước 4: Viết chương trình dùng ngôn ngữ Java trong tệp MainActivity.java“:

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.face.Face;
import com.google.mlkit.vision.face.FaceDetection;
import com.google.mlkit.vision.face.FaceDetector;
import com.google.mlkit.vision.face.FaceDetectorOptions;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {
private ImageView imageView_1;
private ImageView imageView_2;
private Button btn_chonanh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_1 = findViewById(R.id.img_1);
imageView_2 = findViewById(R.id.img_2);
btn_chonanh = findViewById(R.id.btn_chonanh);
ActivityResultLauncher<PickVisualMediaRequest> pickMedia =
registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
// Lệnh được gọi sau khi người dùng chọn một ảnh
//hoặc đóng trình chọn ảnh.
if (uri != null) {
try {
Bitmap bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView_1.setImageBitmap(bitmap);
InputImage image = InputImage.fromBitmap(bitmap, 0);
phat_hien_khuon_mat(image,bitmap);

} catch (IOException e) {
throw new RuntimeException(e);
}
Log.d("PhotoPicker", "Selected URI: " + uri);
} else {
Log.d("PhotoPicker", "No media selected");
}
});

btn_chonanh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Khởi chạy trình chọn ảnh và cho phép người dùng chỉ chọn hình ảnh.
pickMedia.launch(new PickVisualMediaRequest.Builder()
.setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
.build());
}
});
}
private void phat_hien_khuon_mat(InputImage image, Bitmap bitmap){
// High-accuracy landmark detection and face classification
FaceDetectorOptions highAccuracyOpts =
new FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
.build();

FaceDetector detector = FaceDetection.getClient(highAccuracyOpts);
Task<List<Face>> result =
detector.process(image)
.addOnSuccessListener(
new OnSuccessListener<List<Face>>() {
@Override
public void onSuccess(List<Face> faces) {
Bitmap faceBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(faceBitmap);
Paint paint_face = new Paint();
paint_face.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
paint_face.setStyle(Paint.Style.STROKE);
paint_face.setStrokeWidth(5);
paint_face.setColor(Color.parseColor("#18FF00"));
for (Face face : faces) {
Rect bounds = face.getBoundingBox();
canvas.drawRect(bounds,paint_face);
}
imageView_2.setImageBitmap(faceBitmap);
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});

}
}

Sau khi xây dựng ứng dụng thành công, sẽ có kết quả như sau:



Như các bạn thấy, ứng dụng đã phát hiện khuôn mặt của những người trong ảnh. Chúc các bạn thực hiện thành công.

Comments