본문 바로가기

IT개발일지/Android

[Android]얼굴분석 API - MicroSoft Face API

얼굴분석 API - MicroSoft Face API

 

참고 자료

https://docs.microsoft.com/ko-kr/azure/cognitive-services/face/tutorials/faceapiinjavaforandroidtutorial

 

Face SDK 추가

1. Gradle 종속성 추가

build.gradle(Module: app) - com.microsoft.projectoxford:face:1.4.3에 대한 종속성을 추가

 

2. 적용할 액티비티에서 다음과 같이 import문을 추가해줍니다.

import com.microsoft.projectoxford.face.*;
import com.microsoft.projectoxford.face.contract.*;

 

3. 적용할 액티비티에서 다음과 같이 선언해줍니다.

// Add your Face endpoint to your environment variables.
private final String apiEndpoint = System.getenv("FACE_ENDPOINT");
// Add your Face subscription key to your environment variables.
private final String subscriptionKey = System.getenv("FACE_SUBSCRIPTION_KEY");

private final FaceServiceClient faceServiceClient =
        new FaceServiceRestClient(apiEndpoint, subscriptionKey);

private final int PICK_IMAGE = 1;
private ProgressDialog detectionProgressDialog;

 

4. manifest 요소의 직계 하위 항목으로 삽입합니다.

<uses-permission android:name="android.permission.INTERNET" />

 

5. 얼굴 감지함수 적용.

// 얼굴 이미지를 업로드하여 얼굴을 감지합니다.
// 감지 후 프레임생성
private void detectAndFrame(final Bitmap imageBitmap) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
    ByteArrayInputStream inputStream =
            new ByteArrayInputStream(outputStream.toByteArray());

    AsyncTask<InputStream, String, Face[]> detectTask =
            new AsyncTask<InputStream, String, Face[]>() {
                String exceptionMessage = "";

                @Override
                protected Face[] doInBackground(InputStream... params) {
                    try {
                        publishProgress("Detecting...");
                        Face[] result = faceServiceClient.detect(
                                params[0],
                                true,         // returnFaceId
                                false,        // returnFaceLandmarks
                                null          // returnFaceAttributes:
                                /* new FaceServiceClient.FaceAttributeType[] {
                                    FaceServiceClient.FaceAttributeType.Age,
                                    FaceServiceClient.FaceAttributeType.Gender }
                                */

    //* 위 주석된 부분에서 얼굴표정에관한 이모션, 안경착용유무, 등등 얼굴에 관한 데이터를 받아옵니다. 

                        );
                        if (result == null){
                            publishProgress(
                                    "Detection Finished. Nothing detected");
                            return null;
                        }
                        publishProgress(String.format(
                                "Detection Finished. %d face(s) detected",
                                result.length));
                        return result;
                    } catch (Exception e) {
                        exceptionMessage = String.format(
                                "Detection failed: %s", e.getMessage());
                        return null;
                    }
                }

                @Override
                protected void onPreExecute() {
                    //TODO: show progress dialog
                    detectionProgressDialog.show();
                }
                @Override
                protected void onProgressUpdate(String... progress) {
                    //TODO: update progress
                    detectionProgressDialog.setMessage(progress[0]);
                }
                @Override
                protected void onPostExecute(Face[] result) {
                    //TODO: update face frames
                    detectionProgressDialog.dismiss();

                    if(!exceptionMessage.equals("")){
                        showError(exceptionMessage);
                    }
                    if (result == null) return;

                    ImageView imageView = findViewById(R.id.imageView1);
                    imageView.setImageBitmap(
                            drawFaceRectanglesOnBitmap(imageBitmap, result));
                    imageBitmap.recycle();
                }
            };

    detectTask.execute(inputStream);
}

private void showError(String message) {
    new AlertDialog.Builder(this)
            .setTitle("Error")
            .setMessage(message)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }})
            .create().show();
}

 

6. 얼굴 감지된 부분에 사각형 적용.

private static Bitmap drawFaceRectanglesOnBitmap(
        Bitmap originalBitmap, Face[] faces) {
    Bitmap bitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(Color.RED);
    paint.setStrokeWidth(10);
    if (faces != null) {
        for (Face face : faces) {
            FaceRectangle faceRectangle = face.faceRectangle;
            canvas.drawRect(
                    faceRectangle.left,
                    faceRectangle.top,
                    faceRectangle.left + faceRectangle.width,
                    faceRectangle.top + faceRectangle.height,
                    paint);
        }
    }
    return bitmap;
}

 

이상 안드로이드 얼굴분석 API(Face API) 관련 포스팅을 마치겠습니다.