Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 人臉識別實戰——打造你的 HowOld 測年齡 App

編輯:關於 Android 程式設計

引言

前陣子微軟的 HowOldRobot 測年齡網站火遍了整個網路,訪問量一度爆棚。當然,這個服務也有不少讓人哭笑不得的「翻車」時刻——明明很年輕卻被猜老,或者性別判斷完全跑偏。

再比如這種情況……

玩笑歸玩笑,言歸正傳。今天我們就來動手做一個 Android 版的 HowOld,看看如何調用人臉識別能力來猜測年齡與性別。(本文在借鑑社區前輩資料的基礎上做了改進與整理。)

Face++ API

想實現人臉識別,我們需要借助 Face++ 提供的服務。官網地址為 https://www.faceplusplus.com.cn/。使用流程大致如下:

1. 註冊帳號

2. 建立應用

3. 複製 Key 與 Secret

4. 下載 SDK

5. 將 SDK 放入工程的 lib 目錄中即可。

佈局設計

先看介面佈局。整體非常簡單:上方是一張圖片,下方是一個 TextView 加上三個按鈕,分別負責識別、開啟相簿與開啟相機。

MainActivity.xml

<LinearLayout android:background="#F89921" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" tools:context="com.game.howold.MainActivity" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools">
    <ImageView android:id="@+id/face_image" android:layout_gravity="center_horizontal" android:layout_height="0dp" android:layout_marginTop="80dp" android:layout_weight="3" android:layout_width="match_parent" android:scaleType="fitXY" android:src="@drawable/level1">
        <LinearLayout android:gravity="center_horizontal|bottom" android:id="@+id/bottom_layout" android:layout_gravity="center_horizontal" android:layout_height="0dp" android:layout_weight="1" android:layout_width="wrap_content" android:minHeight="80dp" android:orientation="horizontal" android:padding="10dp">
            <TextView android:id="@+id/tip" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_width="wrap_content" android:text="有2只臉" android:textColor="#55000000" android:textSize="20sp" android:text>
            <ImageButton android:background="@drawable/detect" android:id="@+id/detect" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_width="wrap_content">
            <ImageButton android:background="@drawable/photo" android:id="@+id/open_photo" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_width="wrap_content">
            <ImageButton android:background="@drawable/camera" android:id="@+id/open_camera" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_width="wrap_content">
            </ImageButton></ImageButton></ImageButton>
        </LinearLayout>
    </ImageView>
</LinearLayout>

人臉識別工具類

接下來封裝一個識別工具類,負責把傳入的圖片送去做識別並回傳結果。其中 Constant 是常量類,用來存放應用的 Key 與 Secret。

FaceRecognize.class

public class FaceRecognize {
    // 回調接口
    public interface CallBack {
        void success(JSONObject result);   // 識別成功
        void error(FaceppParseException e); // 識別失敗
    }

    // 開始識別
    public static void detect(final Bitmap bitmap, final CallBack callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpRequests request = new HttpRequests(Constant.KEY, Constant.SECRET, true, true);
                Bitmap bmSmall = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bmSmall.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 壓縮圖片
                byte[] datas = baos.toByteArray();
                PostParameters params = new PostParameters();
                params.setImg(datas);
                try {
                    JSONObject result = request.detectionDetect(params);
                    if (callback != null) {
                        callback.success(result);
                    }
                } catch (FaceppParseException e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.error(e);
                    }
                }
            }
        }).start();
    }
}

程序主要邏輯

然後在 MainActivity 中編寫主要邏輯。

MainActivity.class

public class MainActivity extends Activity implements OnClickListener {
    private static final int PICK_CODE = 0X110;    // 從相冊選擇照片
    private static final int TAKE_PICTURE = 0X114; // 照相
    private static final int MSG_SUCCESS = 0X111;  // 識別成功
    private static final int MSG_ERROR = 0X112;    // 識別失敗
    private static final int CROP_PHOTO = 0x115;   // 剪裁圖片
    private ImageButton detect, camera, photo;
    private TextView tip, ageAndgender;
    private ImageView img;
    private Bitmap mPhotoImg;
    private Canvas mCanvas;
    private Paint mPaint;
    private CustomProgressDialog dialog;
    private boolean isCamera = false;
    private Dialog dialogs;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS: // 解析成功
                    dialog.dismiss();
                    JSONObject result = (JSONObject) msg.obj;
                    parseResult(result);
                    img.setImageBitmap(mPhotoImg);
                    break;
                case MSG_ERROR:   // 解析失敗
                    dialog.dismiss();
                    String errorMsg = (String) msg.obj;
                    if (TextUtils.isEmpty(errorMsg)) {
                        tip.setText("Error!!");
                    }
                    break;
                default:
                    break;
            }
        }
    };

在上面的片段中,我們定義了常量與控制項,並透過 Handler 來分別處理「識別成功」與「識別失敗」兩種情況。

/**
 * 解析 JSON 數據
 */
private void parseResult(JSONObject object) {
    Bitmap bitmap = Bitmap.createBitmap(mPhotoImg.getWidth(), mPhotoImg.getHeight(), mPhotoImg.getConfig());
    mCanvas = new Canvas(bitmap);
    mCanvas.drawBitmap(mPhotoImg, 0, 0, null);
    mPaint.setColor(Color.RED);
    mPaint.setAntiAlias(true);
    mPaint.setStrokeWidth(3);
    mPaint.setStrokeCap(Cap.ROUND);
    try {
        JSONArray faces = object.getJSONArray("face");
        int faceCount = faces.length();
        if (faceCount == 0) { // 未識別出人臉
            dialogs = new AlertDialog.Builder(this)
                    .setTitle("檢測結果")
                    .setMessage("長得太抽象o(╯□╰)o,識別不出來")
                    .setNegativeButton("重來", null)
                    .create();
            dialogs.show();
            return;
        }
        tip.setText("發現 " + faceCount + " 只 臉");
        for (int i = 0; i < faceCount; i++) {
            JSONObject face = faces.getJSONObject(i);
            JSONObject position = face.getJSONObject("position");
            float x = (float) position.getJSONObject("center").getDouble("x");
            float y = (float) position.getJSONObject("center").getDouble("y");
            float width = (float) position.getDouble("width");
            float height = (float) position.getDouble("height");
            x = x / 100 * bitmap.getWidth();
            y = y / 100 * bitmap.getHeight();
            width = width / 100 * bitmap.getWidth();
            height = height / 100 * bitmap.getHeight();
            // 繪製臉部識別框
            mCanvas.drawLine(x - width / 2, y - height / 2, x - width / 2, y + height / 2, mPaint);
            mCanvas.drawLine(x - width / 2, y - height / 2, x + width / 2, y - height / 2, mPaint);
            mCanvas.drawLine(x + width / 2, y - height / 2, x + width / 2, y + height / 2, mPaint);
            mCanvas.drawLine(x - width / 2, y + height / 2, x + width / 2, y + height / 2, mPaint);
            int age = face.getJSONObject("attribute").getJSONObject("age").getInt("value");
            String gender = face.getJSONObject("attribute").getJSONObject("gender").getString("value");
            Bitmap ageBitmap = buildAgeBitmap(age, gender.equals("Male"));
            mCanvas.drawBitmap(ageBitmap, x - ageBitmap.getWidth() / 2, y - height / 2 - ageBitmap.getHeight(), null);
            mPhotoImg = bitmap;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

在 parseResult 方法中,我們解析伺服器回傳的 JSON,取出年齡、性別以及臉部位置等資料。由於伺服器回傳的臉部中心座標與寬高是以「圖片百分比」表示的,因此需要換算成真正的像素位置:

float x = (float) position.getJSONObject("center").getDouble("x");
float y = (float) position.getJSONObject("center").getDouble("y");
float width = (float) position.getDouble("width");
float height = (float) position.getDouble("height");
x = x / 100 * bitmap.getWidth();
y = y / 100 * bitmap.getHeight();
width = width / 100 * bitmap.getWidth();
height = height / 100 * bitmap.getHeight();

接著用四條線段畫出示例圖中那個紅色的人臉框:

mCanvas.drawLine(x - width / 2, y - height / 2, x - width / 2, y + height / 2, mPaint);
mCanvas.drawLine(x - width / 2, y - height / 2, x + width / 2, y - height / 2, mPaint);
mCanvas.drawLine(x + width / 2, y - height / 2, x + width / 2, y + height / 2, mPaint);
mCanvas.drawLine(x - width / 2, y + height / 2, x + width / 2, y + height / 2, mPaint);

然後把表示性別與年齡的標籤畫在臉框上方,並對標籤尺寸做校正,避免過大:

int age = face.getJSONObject("attribute").getJSONObject("age").getInt("value");
String gender = face.getJSONObject("attribute").getJSONObject("gender").getString("value");
Bitmap ageBitmap = buildAgeBitmap(age, gender.equals("Male"));
int ageWidth = ageBitmap.getWidth();
int ageHeight = ageBitmap.getHeight();
if (bitmap.getWidth() < img.getWidth() && bitmap.getHeight() < img.getHeight()) {
    float ratio = Math.max(bitmap.getWidth() * 1.0f / img.getWidth(),
                           bitmap.getHeight() * 1.0f / img.getHeight());
    ageBitmap = Bitmap.createScaledBitmap(ageBitmap, (int) (ageWidth * ratio), (int) (ageHeight * ratio), false);
}
mCanvas.drawBitmap(ageBitmap, x - ageBitmap.getWidth() / 2, y - height / 2 - ageBitmap.getHeight(), null);
mPhotoImg = bitmap;

性別年齡標籤其實就是一個 TextView,左側透過 drawableLeft 放置表示性別的圖示。buildAgeBitmap 函式負責把 TextView 轉換成 Bitmap:

private Bitmap buildAgeBitmap(int age, boolean isMale) {
    ageAndgender = (TextView) getLayoutInflater().inflate(R.layout.age_layout, null);
    ageAndgender.setText(age + "歲");
    if (isMale) {
        ageAndgender.setCompoundDrawablesWithIntrinsicBounds(
                getResources().getDrawable(R.drawable.male), null, null, null);
    } else {
        ageAndgender.setCompoundDrawablesWithIntrinsicBounds(
                getResources().getDrawable(R.drawable.female), null, null, null);
    }
    ageAndgender.setDrawingCacheEnabled(true);
    ageAndgender.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                         MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    ageAndgender.layout(0, 0, ageAndgender.getMeasuredWidth(), ageAndgender.getMeasuredHeight());
    ageAndgender.buildDrawingCache();
    return Bitmap.createBitmap(ageAndgender.getDrawingCache());
}

其中 age_layout.xml 就是這個標籤的佈局檔:

age_layout.xml

<TextView android:background="@drawable/hint" android:drawableLeft="@drawable/male" android:gravity="center" android:id="@+id/ageAndgender" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="12" android:textColor="#ffff0000" android:textSize="22sp" android:visibility="invisible" xmlns:android="https://schemas.android.com/apk/res/android" />

拍照、相簿與識別處理

最後,處理底部的拍照、相簿選圖與識別按鈕。

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.open_photo: // 打開相簿選圖
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, PICK_CODE);
            break;
        case R.id.open_camera: // 照相並取得圖片
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date(System.currentTimeMillis());
            String filename = format.format(date);
            File path = Environment.getExternalStorageDirectory();
            File outputImage = new File(path, filename + ".jpg");
            try {
                if (outputImage.exists()) outputImage.delete();
                outputImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageUri = Uri.fromFile(outputImage);
            Intent cameras = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameras.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(cameras, TAKE_PICTURE);
            break;
        case R.id.detect: // 開始識別
            if (mCurrentPhotoPath != null && !mCurrentPhotoPath.trim().equals("")) {
                resizePhoto();
            } else if (!isCamera) {
                mPhotoImg = BitmapFactory.decodeResource(getResources(), R.drawable.level1);
            }
            dialog.show();
            FaceRecognize.recognize(mPhotoImg, new CallBack() {
                @Override
                public void success(JSONObject result) {
                    Message msg = Message.obtain();
                    msg.what = MSG_SUCCESS;
                    msg.obj = result;
                    mHandler.sendMessageDelayed(msg, 500);
                }
                @Override
                public void error(FaceppParseException e) {
                    Message msg = Message.obtain();
                    msg.what = MSG_ERROR;
                    msg.obj = e.getErrorMessage();
                    mHandler.sendMessageDelayed(msg, 500);
                }
            });
            break;
    }
}

在 onActivityResult 回呼中,我們分別處理拍照、相簿選圖與圖片裁剪等操作。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case PICK_CODE: // 從相簿選相片
            if (data != null) {
                Uri uri = data.getData();
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                cursor.moveToFirst();
                int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                mCurrentPhotoPath = cursor.getString(index);
                cursor.close();
                resizePhoto();
                img.setImageBitmap(mPhotoImg);
                tip.setText("Detect-->");
            }
            break;
        case TAKE_PICTURE: // 照相
            if (resultCode == RESULT_OK) {
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(imageUri, "image/*");
                intent.putExtra("scale", true);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 340);
                intent.putExtra("outputY", 340);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intentBc.setData(imageUri);
                this.sendBroadcast(intentBc);
                startActivityForResult(intent, CROP_PHOTO);
            }
            break;
        case CROP_PHOTO: // 剪裁圖片
            try {
                mPhotoImg = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                isCamera = true;
                img.setImageBitmap(mPhotoImg);
                tip.setText("Detect-->");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

特別注意:從相簿選取的圖片往往尺寸很大,必須先縮放,否則容易因記憶體不足而崩潰。resizePhoto 方法就是用來調整圖片大小的:

private void resizePhoto() {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, options);
    double scaleRatio = Math.max(options.outWidth * 1.0d / 1024f, options.outHeight * 1.0d / 1024f);
    options.inSampleSize = (int) Math.ceil(scaleRatio);
    options.inJustDecodeBounds = false;
    mPhotoImg = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
}

測試

最後,來實際跑一下我們的程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved