【Android】测试Face++的人脸识别算法

FacePlusPlus的博客


import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;

import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facepp.error.FaceppParseException;
import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;

import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.json.JSONException;

import android.database.Cursor;
import android.graphics.Canvas;
import android.provider.MediaStore.Images.ImageColumns;

public class MainActivity extends AppCompatActivity {

    final private int PICTURE_CHOOSE = 1;

    private ImageView imageView = null;
    private Bitmap img = null;
    private Button buttonDetect = null;
    private Button buttonFirst = null;
    private TextView textView = null;
    private TextView textViewDebug = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView)this.findViewById(R.id.textView1);
        textViewDebug = (TextView)this.findViewById(R.id.textView2);

        imageView = (ImageView)this.findViewById(R.id.imageView1);

        buttonFirst = (Button)findViewById(R.id.button1);
        buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "You Clicked Button1!", Toast.LENGTH_SHORT).show();
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, PICTURE_CHOOSE);

            }
        });

        buttonDetect = (Button)findViewById(R.id.button2);
        buttonDetect.setVisibility(View.INVISIBLE);
        buttonDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "You Clicked Button2!", Toast.LENGTH_SHORT).show();
                textView.setText("Waiting ...");

                FaceppDetect faceppDetect = new FaceppDetect();
                faceppDetect.setDetectCallback(new DetectCallback() {

                    public void detectResult(JSONObject rst) {
                        //Log.v(TAG, rst.toString());

                        //use the red paint
                        Paint paint = new Paint();
                        paint.setColor(Color.RED);
                        paint.setStrokeWidth(Math.max(img.getWidth(), img.getHeight()) / 100f);

                        //create a new canvas
                        Bitmap bitmap = Bitmap.createBitmap(img.getWidth(), img.getHeight(), img.getConfig());
                        Canvas canvas = new Canvas(bitmap);
                        canvas.drawBitmap(img, new Matrix(), null);

                        try {
                            //find out all faces
                            final int count = rst.getJSONArray("face").length();
                            for (int i = 0; i < count; ++i) {
                                float x, y, w, h;
                                //get the center point
                                x = (float)rst.getJSONArray("face").getJSONObject(i)
                                        .getJSONObject("position").getJSONObject("center").getDouble("x");
                                y = (float)rst.getJSONArray("face").getJSONObject(i)
                                        .getJSONObject("position").getJSONObject("center").getDouble("y");

                                //get face size
                                w = (float)rst.getJSONArray("face").getJSONObject(i)
                                        .getJSONObject("position").getDouble("width");
                                h = (float)rst.getJSONArray("face").getJSONObject(i)
                                        .getJSONObject("position").getDouble("height");

                                //change percent value to the real size
                                x = x / 100 * img.getWidth();
                                w = w / 100 * img.getWidth() * 0.7f;
                                y = y / 100 * img.getHeight();
                                h = h / 100 * img.getHeight() * 0.7f;

                                //draw the box to mark it out
                                canvas.drawLine(x - w, y - h, x - w, y + h, paint);
                                canvas.drawLine(x - w, y - h, x + w, y - h, paint);
                                canvas.drawLine(x + w, y + h, x - w, y + h, paint);
                                canvas.drawLine(x + w, y + h, x + w, y - h, paint);
                            }

                            //save new image
                            img = bitmap;

                            MainActivity.this.runOnUiThread(new Runnable() {
                                public void run() {
                                    //show the image
                                    imageView.setImageBitmap(img);
                                    textView.setText("Finished, "+ count + " faces.");
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            MainActivity.this.runOnUiThread(new Runnable() {
                                public void run() {
                                    textView.setText("Error.");
                                }
                            });
                        }
                    }
                });
                faceppDetect.detect(img);
            }
        });
        imageView.setImageBitmap(img);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode == PICTURE_CHOOSE) {
            if (intent != null) {
                try {
                    //加载图片并显示
                    ContentResolver resolver = getContentResolver();
                    Uri originalUri = intent.getData();//获得图片的uri
                    img = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                    imageView.setImageBitmap(img);

                    //获取图片的路径
                    Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
                    cursor.moveToFirst();
                    int idx = cursor.getColumnIndex(ImageColumns.DATA);
                    String fileSrc = cursor.getString(idx);
                    textViewDebug.setText("Picture:" + fileSrc);

                    textView.setText("图片加载成功!");
                    buttonDetect.setVisibility(View.VISIBLE);
                    }catch (IOException e) {
                    textView.setText("TAG-->Error" + e.toString());
                    }
            }
            else {
                textViewDebug.setText("intent == null");
            }
        }

    }


    private class FaceppDetect {
        DetectCallback callback = null;

        public void setDetectCallback(DetectCallback detectCallback) {
            callback = detectCallback;
        }

        public void detect(final Bitmap image) {

            new Thread(new Runnable() {

                public void run() {
                    HttpRequests httpRequests = new HttpRequests("4480afa9b8b364e30ba03819f3e9eff5", "Pz9VFT8AP3g_Pz8_dz84cRY_bz8_Pz8M", true, false);
                    //Log.v(TAG, "image size : " + img.getWidth() + " " + img.getHeight());

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    float scale = Math.min(1, Math.min(600f / img.getWidth(), 600f / img.getHeight()));
                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap imgSmall = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, false);
                    //Log.v(TAG, "imgSmall size : " + imgSmall.getWidth() + " " + imgSmall.getHeight());

                    imgSmall.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte[] array = stream.toByteArray();
                    try {
                        //detect
                        JSONObject result = httpRequests.detectionDetect(new PostParameters().setImg(array));
                        //finished , then call the callback function
                        if (callback != null) {
                            callback.detectResult(result);
                        }
                    } catch (FaceppParseException e) {
                        e.printStackTrace();
                        MainActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                textView.setText("Network error.");
                            }
                        });
                    }
                }
            }).start();
        }
    }

    interface DetectCallback {
        void detectResult(JSONObject rst);
    }
}


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.duanjiwei.faceplusplusapp.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="加载图片"
        android:id="@+id/button1"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="人脸识别"
        android:id="@+id/button2"
        android:layout_alignTop="@+id/button1"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView1"
        android:layout_below="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NewTextView"
        android:id="@+id/textView1"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NewTextDebug"
        android:id="@+id/textView2"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值