Android人脸识别技术,可以参考下面的网站。
http://www.faceplusplus.com.cn/
本项目使用的就是该网站的api.

项目具体使用的技术代码

  1. /**
  2. * 用来压缩图片的方法
  3. */
  4. private void resizePhoto() {
  5. BitmapFactory.Options options = new Options();
  6. options.inJustDecodeBounds = true;
  7. BitmapFactory.decodeFile(mcurrentPhotoPath, options);
  8. double ratio = Math.max(options.outWidth*1.0d/1024 , options.outHeight*1.0d/1024);
  9. options.inSampleSize = (int)Math.ceil(ratio);
  10. options.inJustDecodeBounds = false;
  11. mphotoImage = BitmapFactory.decodeFile(mcurrentPhotoPath, options);
  12. }
  1. //开启图库
  2. Intent intent = new Intent(Intent.ACTION_PICK);
  3. intent.setType("image/*");
  4. startActivityForResult(intent, PIC_CODE);
  5. 得到图片位置
  6. @Override
  7. protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  8. switch(requestCode) {
  9. //获取图片的路径
  10. case PIC_CODE:
  11. if(null != intent) {
  12. Uri uri = intent.getData();
  13. Cursor cursor = getContentResolver().query( uri, null, null, null, null);
  14. if (cursor==null) {
  15. Log.e("M", "null");
  16. }
  17. cursor.moveToFirst();
  18. int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
  19. mcurrentPhotoPath = cursor.getString(idx);
  20. cursor.close();
  21. resizePhoto();
  22. photoView.setImageBitmap(mphotoImage);
  23. num_detected.setText("");
  24. }
  25. break;

不装逼了,贴代码。
Mainactivity.class

  1. package com.crazylin.facedetected;
  2. import org.json.JSONArray;
  3. import org.json.JSONException;
  4. import org.json.JSONObject;
  5. import android.app.Activity;
  6. import android.content.Intent;
  7. import android.database.Cursor;
  8. import android.graphics.Bitmap;
  9. import android.graphics.BitmapFactory;
  10. import android.graphics.BitmapFactory.Options;
  11. import android.graphics.Canvas;
  12. import android.graphics.Paint;
  13. import android.net.Uri;
  14. import android.os.Bundle;
  15. import android.os.Handler;
  16. import android.os.Message;
  17. import android.provider.MediaStore;
  18. import android.text.TextUtils;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.view.View.OnClickListener;
  22. import android.view.Window;
  23. import android.view.WindowManager;
  24. import android.widget.Button;
  25. import android.widget.ImageView;
  26. import android.widget.TextView;
  27. import com.facepp.error.FaceppParseException;
  28. public class MainActivity extends Activity implements OnClickListener {
  29. private static final int PIC_CODE = 0X110;
  30. private Button getImage_btn, image_detect_btn, capture_btn;
  31. private View loadingView;
  32. private ImageView photoView;
  33. private TextView num_detected;
  34. private String mcurrentPhotoPath;
  35. private Bitmap mphotoImage;
  36. private Handler mhandler;
  37. private Paint mPaint;
  38. private TextView infoText;
  39. @Override
  40. protected void onCreate(Bundle savedInstanceState) {
  41. super.onCreate(savedInstanceState);
  42. requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
  43. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  44. WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
  45. setContentView(R.layout.activity_main);
  46. initView();
  47. initEvent();
  48. initHandler();
  49. mPaint = new Paint();
  50. }
  51. private void initHandler() {
  52. mhandler = new Handler() {
  53. @Override
  54. public void handleMessage(Message msg) {
  55. switch(msg.what) {
  56. case RESULT_OK:
  57. loadingView.setVisibility(View.GONE);
  58. JSONObject json = (JSONObject) msg.obj;
  59. prepareResultBitmap(json);
  60. photoView.setImageBitmap(mphotoImage);
  61. break;
  62. case RESULT_CANCELED:
  63. loadingView.setVisibility(View.GONE);
  64. String errorMessage = (String) msg.obj;
  65. if(TextUtils.isEmpty(errorMessage)) {
  66. num_detected.setText("Error");
  67. }else {
  68. num_detected.setText(errorMessage);
  69. }
  70. break;
  71. }
  72. }
  73. };
  74. }
  75. private void prepareResultBitmap(JSONObject json) {
  76. Bitmap bitmap = Bitmap.createBitmap(mphotoImage.getWidth(), mphotoImage.getHeight(), mphotoImage.getConfig());
  77. Canvas canvas = new Canvas(bitmap);
  78. canvas.drawBitmap(mphotoImage, 0, 0, null);
  79. try {
  80. JSONArray faces = json.getJSONArray("face");
  81. int faceCount = faces.length();
  82. num_detected.setText("find : " + faceCount);
  83. for(int i=0; i<faceCount; i++) {
  84. //单独的face对象
  85. JSONObject face = faces.getJSONObject(i);
  86. int age = face.getJSONObject("attribute").getJSONObject("age").getInt("value");
  87. String gender = face.getJSONObject("attribute").getJSONObject("gender").getString("value");
  88. //String race = face.getJSONObject("attribute").getJSONObject("race").getString("value");
  89. Bitmap infoBitmap = BuildBitmapInfo(age, gender);
  90. int infoWidth = infoBitmap.getWidth();
  91. int infoHeight = infoBitmap.getHeight();
  92. if((bitmap.getWidth() < photoView.getWidth())&&(bitmap.getHeight() < photoView.getHeight())) {
  93. float ratio = Math.max(bitmap.getWidth()*1.0f/photoView.getWidth(), bitmap.getHeight()*1.0f/photoView.getHeight());
  94. infoBitmap = Bitmap.createScaledBitmap(infoBitmap, (int)(infoWidth * ratio), (int)(infoHeight * ratio), false);
  95. }
  96. JSONObject position = face.getJSONObject("position");
  97. float x = (float) position.getJSONObject("center").getDouble("x");
  98. float y = (float) position.getJSONObject("center").getDouble("y");
  99. float w = (float) position.getDouble("width");
  100. float h = (float) position.getDouble("height");
  101. x = x/100*bitmap.getWidth();
  102. y = y/100*bitmap.getHeight();
  103. w = w/100*bitmap.getWidth();
  104. h = h/100*bitmap.getHeight();
  105. mPaint.setColor(0xffffffff);
  106. canvas.drawLine(x - w/2, y - h/2, x - w/2, y + h/2, mPaint);
  107. canvas.drawLine(x - w/2, y - h/2, x + w/2, y - h/2, mPaint);
  108. canvas.drawLine(x + w/2, y - h/2, x + w/2, y + h/2, mPaint);
  109. canvas.drawLine(x - w/2, y + h/2, x + w/2, y + h/2, mPaint);
  110. canvas.drawBitmap(infoBitmap, x - infoBitmap.getWidth()/2, y - h/2 - infoBitmap.getHeight(), null);
  111. mphotoImage = bitmap;
  112. }
  113. } catch (JSONException e) {
  114. e.printStackTrace();
  115. }
  116. }
  117. private Bitmap BuildBitmapInfo(int age, String gender) {
  118. System.out.println(gender + " age:" + age);
  119. infoText.setText(gender + " age:" + age );
  120. infoText.setDrawingCacheEnabled(true);
  121. Bitmap bitmap = Bitmap.createBitmap(infoText.getDrawingCache());
  122. infoText.destroyDrawingCache();
  123. return bitmap;
  124. }
  125. private void initEvent() {
  126. getImage_btn.setOnClickListener(this);
  127. image_detect_btn.setOnClickListener(this);
  128. capture_btn.setOnClickListener(this);
  129. }
  130. private void initView() {
  131. getImage_btn = (Button) findViewById(R.id.get_image);
  132. image_detect_btn = (Button) findViewById(R.id.detect_image);
  133. capture_btn = (Button) findViewById(R.id.capture_image);
  134. loadingView = findViewById(R.id.loading);
  135. photoView = (ImageView) findViewById(R.id.photo_image);
  136. num_detected = (TextView) findViewById(R.id.num_detected);
  137. infoText = (TextView) findViewById(R.id.info_text);
  138. }
  139. @Override
  140. protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  141. switch(requestCode) {
  142. //获取图片的路径
  143. case PIC_CODE:
  144. if(null != intent) {
  145. Uri uri = intent.getData();
  146. Cursor cursor = getContentResolver().query( uri, null, null, null, null);
  147. if (cursor==null) {
  148. Log.e("M", "null");
  149. }
  150. cursor.moveToFirst();
  151. int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
  152. mcurrentPhotoPath = cursor.getString(idx);
  153. cursor.close();
  154. resizePhoto();
  155. photoView.setImageBitmap(mphotoImage);
  156. num_detected.setText("");
  157. }
  158. break;
  159. case 2:
  160. Bitmap bmPhoto = (Bitmap) intent.getExtras().get("data");
  161. mcurrentPhotoPath = "capturing";
  162. mphotoImage = bmPhoto;
  163. photoView.setImageBitmap(mphotoImage);
  164. num_detected.setText("");
  165. break;
  166. }
  167. }
  168. /**
  169. * 用来压缩图片的方法
  170. */
  171. private void resizePhoto() {
  172. BitmapFactory.Options options = new Options();
  173. options.inJustDecodeBounds = true;
  174. BitmapFactory.decodeFile(mcurrentPhotoPath, options);
  175. double ratio = Math.max(options.outWidth*1.0d/1024 , options.outHeight*1.0d/1024);
  176. options.inSampleSize = (int)Math.ceil(ratio);
  177. options.inJustDecodeBounds = false;
  178. mphotoImage = BitmapFactory.decodeFile(mcurrentPhotoPath, options);
  179. }
  180. @Override
  181. public void onClick(View v) {
  182. switch(v.getId()) {
  183. case R.id.get_image:
  184. Intent intent = new Intent(Intent.ACTION_PICK);
  185. intent.setType("image/*");
  186. startActivityForResult(intent, PIC_CODE);
  187. break;
  188. case R.id.capture_image:
  189. Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  190. startActivityForResult(intent2, 2);
  191. break;
  192. case R.id.detect_image:
  193. loadingView.setVisibility(View.VISIBLE);
  194. if(mcurrentPhotoPath!=null && !mcurrentPhotoPath.trim().equals("")) {
  195. if(mcurrentPhotoPath.equals("capturing")) {
  196. }else {
  197. resizePhoto();
  198. }
  199. }else {
  200. mphotoImage = BitmapFactory.decodeResource(getResources(), R.drawable.brother2);
  201. }
  202. FaceDetect.detect(mphotoImage, new FaceDetect.Callback() {
  203. @Override
  204. public void success(JSONObject result) {
  205. Message msg = Message.obtain(mhandler);
  206. msg.what = RESULT_OK;
  207. msg.obj = result;
  208. msg.sendToTarget();
  209. }
  210. @Override
  211. public void error(FaceppParseException exception) {
  212. Message msg = Message.obtain(mhandler);
  213. msg.what = RESULT_CANCELED;
  214. msg.obj = exception.getErrorMessage();
  215. msg.sendToTarget();
  216. }
  217. });
  218. break;
  219. }
  220. }
  221. }
  222. </code></pre>

mainactivity的对应布局文件

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content" >
  4. <Button
  5. android:id="@+id/get_image"
  6. android:layout_width="wrap_content"
  7. android:layout_height="wrap_content"
  8. android:layout_alignParentBottom="true"
  9. android:layout_alignParentRight="true"
  10. android:layout_marginRight="10dp"
  11. android:text="Get Image" />
  12. <Button
  13. android:id="@+id/detect_image"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:layout_alignParentBottom="true"
  17. android:layout_marginRight="10dp"
  18. android:layout_toLeftOf="@+id/get_image"
  19. android:text="Detect" />
  20. <TextView
  21. android:id="@+id/num_detected"
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:layout_alignParentBottom="true"
  25. android:layout_marginRight="10dp"
  26. android:layout_toLeftOf="@+id/detect_image"
  27. android:layout_alignTop="@+id/detect_image"
  28. android:gravity="center"
  29. android:text="find: 0" />
  30. <ImageView
  31. android:id="@+id/photo_image"
  32. android:layout_width="wrap_content"
  33. android:layout_height="wrap_content"
  34. android:layout_above="@+id/detect_image"
  35. android:layout_alignParentLeft="true"
  36. android:layout_alignParentRight="true"
  37. android:layout_alignParentTop="true"
  38. android:src="@drawable/brother2"/>
  39. <FrameLayout
  40. android:id="@+id/loading"
  41. android:layout_width="match_parent"
  42. android:layout_height="match_parent"
  43. android:clickable="true"
  44. android:visibility="gone">
  45. <ProgressBar
  46. android:layout_width="wrap_content"
  47. android:layout_height="wrap_content"
  48. android:layout_gravity="center"
  49. />
  50. <TextView
  51. android:id="@+id/info_text"
  52. android:layout_width="wrap_content"
  53. android:layout_height="wrap_content"
  54. android:visibility="invisible"
  55. android:textColor="#AEEEEEff"
  56. android:layout_gravity="center"
  57. android:textSize="18sp"
  58. android:text=" "
  59. />
  60. </FrameLayout>
  61. <Button
  62. android:id="@+id/capture_image"
  63. android:layout_width="wrap_content"
  64. android:layout_height="wrap_content"
  65. android:layout_alignBaseline="@+id/num_detected"
  66. android:layout_alignBottom="@+id/num_detected"
  67. android:layout_alignParentLeft="true"
  68. android:text="Capture" />
  69. </RelativeLayout>

常量类

  1. package com.crazylin.facedetected;
  2. public class Constant {
  3. public static final String KEY = "a9f32d6fd94da04bc162caabe7e87400";
  4. public static final String SECRET = "BP9B_33cGnuwPOi4cq2bqNTTTeeLb3cV";
  5. }

请求数据类

  1. package com.crazylin.facedetected;
  2. import java.io.ByteArrayOutputStream;
  3. import org.json.JSONObject;
  4. import android.graphics.Bitmap;
  5. import android.util.Log;
  6. import com.facepp.error.FaceppParseException;
  7. import com.facepp.http.HttpRequests;
  8. import com.facepp.http.PostParameters;
  9. public class FaceDetect {
  10. public interface Callback {
  11. void success(JSONObject result);
  12. void error(FaceppParseException exeception);
  13. }
  14. public static void detect(final Bitmap bm,final Callback callback) {
  15. new Thread(new Runnable() {
  16. @Override
  17. public void run() {
  18. try {
  19. //向Face++服务器提交请求
  20. System.out.println("向Face++服务器提交请求");
  21. HttpRequests requests = new HttpRequests(Constant.KEY, Constant.SECRET, true, true);
  22. Bitmap bmsmall = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight());
  23. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  24. bmsmall.compress(Bitmap.CompressFormat.JPEG, 50, stream);
  25. byte[] bytes = stream.toByteArray();
  26. PostParameters params = new PostParameters();
  27. params.setImg(bytes);
  28. JSONObject json = requests.detectionDetect(params);
  29. Log.e("Tag", json.toString());
  30. if (null != callback) {
  31. callback.success(json);
  32. }
  33. } catch (FaceppParseException e) {
  34. System.out.println(e.toString());
  35. e.printStackTrace();
  36. if(null != callback) {
  37. callback.error(e);
  38. }
  39. }
  40. }
  41. }).start();
  42. }
  43. }

ok,需要的尽管拿走吧。
下载地址
http://download.csdn.net/detail/u013270444/9437964

版权声明:本文为caoxinyu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/caoxinyu/p/6647950.html