1. 创建应用,获取API Key和API Secret
首先进入习悦开发者平台,注册或登录成功后,点击创建应用,填写必要内容后创建应用,如图:
创建应用后,在我的应用模块,选择对应应用点击管理应用,如图:
复制API Key和API Secret以备后用,如图:
2. 下载人脸识别SDK
- 进入SDK下载页面下载好人脸SDK文件,把SDK文件拉进项目并进行配置,并根据配置流程进行SDK启动配置;
3. 实现年龄性别检测
-
完成SDK初始化后,使用UserManage工具先进行用户绑定,用户绑定后才能进行其他操作,代码如下:
UserManage.newInstance(this).bindUser(userId, new UserBindListener() {
@Override
public void onUserBind(String userId, ErrorMsg error) {
dialog.dismiss();
if (error.getCode() == 0){
Toast.makeText(BindUserActivity.this,"绑定成功!", Toast.LENGTH_SHORT).show();}else { Toast.makeText(BindUserActivity.this, error.getMsg(), Toast.LENGTH_SHORT).show(); } } });
-
然后利用SDK中的DetectManage工具对图片进行人脸检测获取年龄性别数据,代码如下:
btn_check = (Button) findViewById(R.id.btn_check);
btn_check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DetectManage.newInstance(FaceRegionDetectActivity.this).getFaceRegion(bitmap, true, true, new FaceRegionCheckListener() {
@Override
public void onFaceRegionCheck(FaceInfo faceInfo, ErrorMsg error) {
dialog.dismiss();
//判断是否成功
if (error.getCode() == 0) {
if (faceInfo.getFaceNum() == 0) {
Toast.makeText(FaceRegionDetectActivity.this, "没有检测到人脸数据!", Toast.LENGTH_SHORT).show();
return;
}
//复制图片bitmap进行绘画操作
Bitmap myBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(myBitmap);
//新建文字画笔
Paint txt = new Paint();
txt.setStrokeWidth(6);
int size = bitmap.getWidth() / 18;
txt.setTextSize(size);
txt.setTextAlign(Paint.Align.LEFT);
txt.setColor(Color.RED);//新建画框画笔 Paint mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.GREEN); mPaint.setDither(true); mPaint.setStrokeWidth(6); mPaint.setStyle(Paint.Style.STROKE); //遍历检测到的所有人脸 for (int i = 0; i < faceInfo.getFace().size(); i++) { Face face = faceInfo.getFace().get(i); FacePosition info = face.getPosition(); Rect rect = new Rect(); rect.set(info.getLeft(), info.getTop(), info.getRight(), info.getBottom()); canvas.save(); canvas.drawRect(rect, mPaint); //画框 //绘画年龄性别文字 canvas.drawText("年龄:" + face.getAttribute().getAge(), (info.getLeft() + (info.getRight() - info.getLeft())) / 2, info.getTop() + (info.getBottom() - info.getTop()) / 2, txt); canvas.drawText("女:" + (float) (face.getAttribute().getGender().get(0) * 100) + "% 男" + (float) (face.getAttribute().getGender().get(1) * 100) + "%", (info.getLeft() + (info.getRight() - info.getLeft())) / 2, (info.getTop() + (info.getBottom() - info.getTop()) / 2) + 60, txt); } canvas.restore(); img_show.setImageBitmap(myBitmap); //重新显示图片 } } }); } });
实现效果