这是我下载的一个人脸识别的demo,然后修改了一下,现在可以用矩形框圈住人脸了,以下为一部分代码,还可以下载源码。
package com.facpp.picturedetect;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.facepp.error.FaceppParseException;
import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;
import com.facepp.result.FaceppResult;
/**
* A simple demo, get a picture form your phone<br />
* Use the facepp api to detect<br />
* Find all face on the picture, and mark them out.
* @author moon5ckq
*/
public class MainActivity extends Activity {
final private static String TAG = "MainActivity";
final private int PICTURE_CHOOSE = 1;
private String api_key = "45b03265580e67d98ec9b0c9503fdb57";
private String api_secret = "RUUlaCJAu6Fuzs9dx-bFCMJz1mecvjhO";
private ImageView imageView = null;
private Bitmap img = null;
private Button buttonDetect = null;
private TextView textView = null;
List<HashMap<String, String>> faceList = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)this.findViewById(R.id.button1);
//获取图片
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//get a picture form your phone
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PICTURE_CHOOSE);
}
});
textView = (TextView)this.findViewById(R.id.textView1);
buttonDetect = (Button)this.findViewById(R.id.button2);
buttonDetect.setVisibility(View.INVISIBLE);
buttonDetect.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
textView.setText("Waiting ...");
FaceppDetect faceppDetect = new FaceppDetect();
faceppDetect.setDetectCallback(new DetectCallback() {
public void detectResult(FaceppResult rst) {
//使用红色线条
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(Math.max(img.getWidth(), img.getHeight()) / 100f);
//新建一个canvas
Bitmap bitmap = Bitmap.createBitmap(img.getWidth(), img.getHeight(), img.getConfig());
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(img, new Matrix(), null);
try {
//查找所有人脸
final int count = rst.get("face").getCount();
for (int i = 0; i < count; ++i) {
JSONObject result = new JSONObject(rst.toString());
faceList = JsonParser.parseFaceResult(result);
float x, y, w, h;
//获取中心点
x = Float.valueOf(faceList.get(i).get("center_x"));
y = Float.valueOf(faceList.get(i).get("center_y"));
//获取脸的尺寸
w = Float.valueOf(faceList.get(i).get("width"));
h = Float.valueOf(faceList.get(i).get("height"));
//将所有值变成真实的尺寸
x = x / 100 * img.getWidth();
w = w / 100 * img.getWidth() * 0.7f;
y = y / 100 * img.getHeight();
h = h / 100 * img.getHeight() * 0.7f;
//画出矩形
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);
}
//保存图片
img = bitmap;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
//show the image
imageView.setImageBitmap(img);
textView.setText("Finished, "+ count + " faces.");
}
});
} catch (FaceppParseException e) {
e.printStackTrace();
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
textView.setText("Error.");
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
faceppDetect.detect(img);
}
});
imageView = (ImageView)this.findViewById(R.id.imageView1);
imageView.setImageBitmap(img);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
//the image picker callback
if (requestCode == PICTURE_CHOOSE) {
if (intent != null) {
//The Android api ~~~
//Log.d(TAG, "idButSelPic Photopicker: " + intent.getDataString());
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
//Log.d(TAG, "Picture:" + fileSrc);
//just read size
Options options = new Options();
options.inJustDecodeBounds = true;
img = BitmapFactory.decodeFile(fileSrc, options);
//scale size to read
options.inSampleSize = Math.max(1, (int)Math.ceil(Math.max((double)options.outWidth / 1024f, (double)options.outHeight / 1024f)));
options.inJustDecodeBounds = false;
img = BitmapFactory.decodeFile(fileSrc, options);
textView.setText("Clik Detect. ==>");
imageView.setImageBitmap(img);
buttonDetect.setVisibility(View.VISIBLE);
}
else {
Log.d(TAG, "idButSelPic Photopicker canceled");
}
}
}
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(api_key, api_secret);
//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
FaceppResult 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(FaceppResult rst);
}
}
源代码下载:PictureDetect.zip