本文地址:http://blog.csdn.net/tiandixuanwuliang/article/details/78018687

本文将介绍如何使用face++的API接口实现人脸识别。

一、获取face++的API支持

1.1face++官网:https://www.faceplusplus.com.cn/

1.2在face++官网上注册账号,填写开发者资料,如下图:

二、创建API Key和绑定Bundle ID

2.1在如下图位置,点击API Key

2.2点击创建API key,按照要求填写(选择试用):

2.3绑定应用程序:

至此,我们的准备工作就做好了。我们将会使用API Key和API Secret。

三、创建Android工程

3.1建立Android项目。本文使用Fragment+Activity模式,Activity代码是简单的fragment,如下

package com.wllfengshu.boyandgirl;import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;public class MainActivity extends Activity {private FragmentManager fm;private FragmentTransaction transaction;@SuppressLint("NewApi")@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);fm = getFragmentManager();transaction = fm.beginTransaction();transaction.replace(R.id.ll_fregment, new FaceFragment());transaction.commit();}public void change(View v) {transaction = fm.beginTransaction();switch (v.getId()) {case R.id.ib_main_face:transaction.replace(R.id.ll_fregment, new FaceFragment());break;case R.id.ib_main_gesture:transaction.replace(R.id.ll_fregment, new GestureFragment());break;case R.id.ib_main_other:transaction.replace(R.id.ll_fregment, new OtherFragment());break;}transaction.commit();}
}

3.2fragment代码如下:(其中封装的函数会在下文中介绍)

package com.wllfengshu.boyandgirl;import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import org.json.JSONException;
import org.json.JSONObject;import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;import com.wllfengshu.util.Constant;
import com.wllfengshu.util.DrawUtil;
import com.wllfengshu.util.GifView;
import com.wllfengshu.util.HttpUtils;
import com.wllfengshu.util.ImageUtil;@SuppressLint({ "NewApi", "HandlerLeak" })
public class FaceFragment extends Fragment implements OnClickListener {private ImageView iv_face;// 锟矫伙拷选锟斤拷锟酵计�private Button ib_face_enter;// 确锟斤拷锟斤拷钮private Button ib_face_choice;// 选锟斤拷图片锟斤拷钮锟斤拷锟斤拷图锟解)private TextView tv_face_gender;private TextView tv_face_age;private TextView tv_face_beauty;private Bitmap scalingPhoto;// 位图private String gender;// 性别private int age;// 年龄private int beauty;// 颜值private Paint paint;// 画笔工具private View view;private GifView gif;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.fragment_face, container, false);iv_face = (ImageView) view.findViewById(R.id.iv_face);ib_face_enter = (Button) view.findViewById(R.id.ib_face_enter);ib_face_choice = (Button) view.findViewById(R.id.ib_face_choice);tv_face_gender = (TextView) view.findViewById(R.id.tv_face_gender);tv_face_age = (TextView) view.findViewById(R.id.tv_face_age);tv_face_beauty = (TextView) view.findViewById(R.id.tv_face_beauty);gif = (GifView) view.findViewById(R.id.gif);ib_face_enter.setOnClickListener(this);ib_face_choice.setOnClickListener(this);paint = new Paint();// 创建画笔scalingPhoto = BitmapFactory.decodeResource(this.getResources(),R.drawable.defualt);return view;}@SuppressLint("HandlerLeak")private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {String str = (String) msg.obj;System.out.println("*******face:" + str);if (str.equals("403") || str.equals("400") || str.equals("413")|| str.equals("500")) {Toast.makeText(getActivity(), "Please Try Again",Toast.LENGTH_SHORT).show();} else {try {JSONObject resultJSON = new JSONObject(str);System.out.println(resultJSON.getString("faces") + "=====");if (resultJSON.getString("faces").equals("[]")) {Toast.makeText(getActivity(),"There is no face picture", Toast.LENGTH_SHORT).show();} else {@SuppressWarnings("rawtypes")List res = DrawUtil.FacePrepareBitmap(resultJSON,scalingPhoto, paint, iv_face);gender = (String) res.get(0);age = (Integer) res.get(1);beauty = (Integer) res.get(2);System.out.println("------------" + gender + " " + age+ " " + " " + beauty);tv_face_gender.setText("性别:"+ ImageUtil.getFaceGender(gender));tv_face_age.setText("年龄:" + age);tv_face_beauty.setText("颜值:" + beauty);}} catch (JSONException e) {e.printStackTrace();}}gif.setVisibility(View.GONE);// 停止gif};};@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == 1) {// 锟矫伙拷选锟斤拷锟酵计拷锟斤拷锟斤拷锟斤拷荽锟斤拷锟絛ata锟斤拷if (data != null) {// 锟矫碉拷图片锟斤拷路锟斤拷String photoPath = ImageUtil.getPhotoPath(getActivity(), data);// 锟斤拷锟斤拷scalingPhoto = ImageUtil.getScalingPhoto(photoPath);// 锟斤拷示图片iv_face.setImageBitmap(scalingPhoto);}}super.onActivityResult(requestCode, resultCode, data);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.ib_face_choice:// 锟斤拷图锟斤拷Intent intent = new Intent();intent.setAction(Intent.ACTION_PICK);intent.setType("image/*");startActivityForResult(intent, 1);// 通锟斤拷氐锟斤拷蚩锟斤拷锟�break;case R.id.ib_face_enter:// 显示加载动画gif.setVisibility(View.VISIBLE);gif.setMovieResource(R.raw.red); // 设置背景gif图片资源String base64ImageEncode = ImageUtil.getBase64ImageEncode(scalingPhoto);System.out.println(base64ImageEncode);// 锟斤拷装锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�final Map<String, Object> map = new HashMap<String, Object>();map.put("api_key", Constant.API_KEY);map.put("api_secret", Constant.API_SECRET);map.put("return_attributes", "gender,age,beauty");map.put("image_base64", base64ImageEncode);// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷new Thread(new Runnable() {@Overridepublic void run() {try {String result = HttpUtils.post(Constant.URL_DETECT, map);Message message = new Message();message.obj = result;handler.sendMessage(message);} catch (IOException e) {e.printStackTrace();}}}).start();break;}}
} 

上面代码说明:fragment页面中包含两个按钮,一个按钮点击“打开手机图库”,一个按钮点击“确认”。用户点击确认后,开始把用户选择的人脸图片通过POST请求方式发送到face++服务器,等待获取人脸特征的数据。
其中封装的POST请求代码如下:

public static String post(String url, Map<String, Object> args) throws IOException {URL host = new URL(url);HttpURLConnection connection = HttpURLConnection.class.cast(host.openConnection());connection.setRequestMethod("POST");connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setRequestProperty("Connection", "Keep-Alive");connection.setRequestProperty("Charsert", "UTF-8");DataOutputStream dos = new DataOutputStream(connection.getOutputStream());if (args != null) {for (Entry<String, Object> entry : args.entrySet()) {String key = entry.getKey(); Object value = entry.getValue();if (value instanceof File) {value = new FileInputStream(File.class.cast(value));}if (value instanceof InputStream) {dos.write((key + "=").getBytes());InputStream is = InputStream.class.cast(value);byte[] data = new byte[is.available()];is.read(data);dos.write(URLEncoder.encode(Base64.encodeToString(data, data.length), "UTF-8").getBytes());is.close();} else { dos.write((key + "=" + URLEncoder.encode(String.valueOf(value), "UTF-8")).getBytes());}dos.write("&".getBytes());}}dos.flush();dos.close();int resultCode = connection.getResponseCode();StringBuilder response = new StringBuilder();if (resultCode == HttpURLConnection.HTTP_OK) {BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = br.readLine()) != null) {response.append(line);}br.close();} else {response.append(resultCode);}return response.toString();}

本文采用把图片转换为base64格式进行传输,其代码如下:

public static String getBase64ImageEncode(Bitmap myImage) {Bitmap bmSmall = Bitmap.createBitmap(myImage, 0, 0, myImage.getWidth(), myImage.getHeight());ByteArrayOutputStream stream = new ByteArrayOutputStream();bmSmall.compress(Bitmap.CompressFormat.JPEG, 100, stream);byte[] arrays = stream.toByteArray();// base64 encodebyte[] encode = Base64.encode(arrays, Base64.DEFAULT);String base64Encode = new String(encode);return base64Encode;}
界面布局文件代码(activity_main.xml文件):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/bg" ><LinearLayoutandroid:id="@+id/ll_fregment"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:orientation="horizontal" ><RadioGroupandroid:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal" ><RadioButtonandroid:id="@+id/ib_main_face"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@drawable/rb_select"android:button="@null"android:checked="true"android:gravity="center"android:onClick="change"android:text="人脸识别" /><RadioButtonandroid:id="@+id/ib_main_gesture"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@drawable/rb_select"android:button="@null"android:gravity="center"android:onClick="change"android:text="手势识别" /><RadioButtonandroid:id="@+id/ib_main_other"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@drawable/rb_select"android:button="@null"android:gravity="center"android:onClick="change"android:text="其他功能" /></RadioGroup></LinearLayout></RelativeLayout>

人脸识别界面代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:text="人脸识别"android:textSize="20sp" /><ImageViewandroid:id="@+id/iv_face"android:layout_width="200dp"android:layout_height="300dp"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:contentDescription="人脸图片"android:paddingTop="40dp"android:src="@drawable/defualt" /><LinearLayoutandroid:id="@+id/ll_button"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@id/iv_face"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:gravity="center_horizontal"android:orientation="horizontal" ><Buttonandroid:id="@+id/ib_face_enter"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/enter"android:text="确定" /><Buttonandroid:id="@+id/ib_face_choice"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/choose"android:text="选择图片" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_below="@id/ll_button"android:orientation="horizontal"android:paddingTop="20dp" ><TextViewandroid:id="@+id/tv_face_gender"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="center"android:src="@drawable/ic_launcher"android:text="性别"android:textSize="20sp" /><TextViewandroid:id="@+id/tv_face_age"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="center"android:src="@drawable/ic_launcher"android:text="年龄"android:textSize="20sp" /><TextViewandroid:id="@+id/tv_face_beauty"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:gravity="center"android:src="@drawable/ic_launcher"android:text="颜值"android:textSize="20sp" /></LinearLayout><com.wllfengshu.util.GifViewandroid:id="@+id/gif"android:layout_width="200dp"android:layout_height="200dp"android:layout_centerHorizontal="true"android:layout_gravity="center_horizontal"android:layout_marginTop="60dp"android:enabled="false" />
</RelativeLayout>

人脸识别界面:

本文还有一些其他的封装函数,由于篇幅问题不一一粘贴,请大家自行下载本文代码案例:
下载地址:http://download.csdn.net/download/tiandixuanwuliang/9984027

使用face++的API接口-人脸识别相关推荐

  1. JavaWeb使用百度人工智能API实现人脸识别登录,人脸注册

    1.JavaWeb使用百度API实现人脸识别 本篇博客使用的环境是SSM+Maven+JSP实现人脸识别登录,适合于JavaWeb的开发(其他语言也可以作为参考),我会从注册百度云账号,前台如何调用摄 ...

  2. python3调用百度API完成人脸识别,检测人种-年龄-性别-颜值-眼镜

    https://ai.baidu.com/docs#/Face-Detect/top 这个是百度人脸识别api 参考博客:https://blog.csdn.net/qq_38412868/artic ...

  3. 树莓派+百度api实现人脸识别

    title: 树莓派+百度api实现人脸识别 tags: 树莓派 date: 2018-5-31 20:06:00 --- 树莓派对接百度api 我以前玩安卓的时候一直用的讯飞的平台和api,对于百度 ...

  4. 使用Azure人脸API对图片进行人脸识别

    人脸识别是人工智能机器学习比较成熟的一个领域.人脸识别已经应用到了很多生产场景.比如生物认证,人脸考勤,人流监控等场景.对于很多中小功能由于技术门槛问题很难自己实现人脸识别的算法.Azure人脸API ...

  5. python调用(百度云、腾讯云)API接口表格识别并保存为excel

    Python表格识别 图像识别具有较高的商业价值,本节主要通过python调用(百度云.腾讯云)API接口表格识别并保存为excel分析表格识别的能力: 提示:需分别申请密钥,在相应位置添加自己密钥即 ...

  6. 如何评价美颜api中人脸识别和人脸检测的准确度?

    人脸识别和人脸检测识别是美颜api中的技术支撑之一,在理想状态下,人脸识别准确率越高越好,但实际情况中,经常会受到逆光.暗光.强光.识别角度等诸多实际因素的影响,因此,脱离使用场景单独考量算法的识别准 ...

  7. 调用face++平台api进行人脸识别

    转载请注明出处:http://blog.csdn.net/hongbin_xu 或 http://hongbin96.com/ 文章链接:http://blog.csdn.net/hongbin_xu ...

  8. SpringBoot+百度云API 实现人脸识别功能

    Java项目分享 缺项目经验的请看过来 2篇原创内容 公众号 前言 去年在公司参与了一个某某机场建设智能机场的一个项目,人脸登机是其中的一个功能模块,当时只是写了后台的接口,调用人脸识别设备的api, ...

  9. java 调用百度接口人脸识别

    项目需要做一个人脸识别打卡的功能,这几天花时间做了一下 1:首先进入[百度人脸接口平台] 2:进入人脸识别 3:创建应用 4:创建完成后可以查看appId,API key,Secret Key 5:把 ...

最新文章

  1. 业绩-----我觉得最难得不是写代码,而是写业绩表
  2. 第九章 关联数组/哈希表
  3. 掌握 Linux 调试技术
  4. 视觉slam第一讲——
  5. java sftp_JAVA 实现SFTP服务器功能
  6. 集成 FileDownloader 总结
  7. 扫地阿姨看完都学会了!写给即将正在找工作的Java攻城狮,砥砺前行!
  8. 我的理想 计算机 作文,我的理想作文(精选15篇)
  9. 泛型中的 T、E、K、V,还记得嘛?
  10. c语言can收发数据原理,汽车车载网络CAN收发器作用和工作原理
  11. 测试适合染发颜色的软件,5秒测出你适合染什么颜色的头发!准到爆!
  12. oracle中text是什么意思,ORACLE TEXT是什么
  13. Java自学之路——构造器(Constructor)
  14. 5000元起家,40年4万倍!一个来自贫民窟的亿万富翁
  15. Python的format用法详解
  16. 图(八):强连通分量
  17. python爬取json数据与实际不一样_Python如何爬取Json数据
  18. sumo笔记(三)——让小车跑起来(rou文件的生成)
  19. [APIO2017]斑斓之地——可持久化线段树
  20. 【python实现网络爬虫(14)】python爬取酷狗中多类型音乐步骤详解(附全部源代码)

热门文章

  1. 如何使用Socks5代理IP加密Windows网络数据传输
  2. 误删除了linux的raid1,RAID管理与恢复误删除文件
  3. 程序员的自我进化:互联网公司套路多,如何避免自己被无偿辞退?
  4. localhost与127.0.0.1
  5. 什么是3D摄影机,与普通摄影机有什么不同?
  6. 被11整除的四位偶数c语言,位和位差-什么叫奇数位和偶数位?能被11整除的数,奇 – 手机爱问...
  7. 少儿编程和机器人编程哪个更好一点
  8. 【JAVA】科研信息管理系统
  9. 杂谈:一张图片引发的版权问题
  10. pycharm调试时显示图片