当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 小程序实现人脸识别功能(百度ai)

小程序实现人脸识别功能(百度ai)

2019年01月08日  | 移动技术网IT编程  | 我要评论

本文介绍了小程序实现人脸识别功能,分享给大家,具体如下:

文档中心:https://ai.baidu.com/docs#/begin/a2bbf4b2

接入流程

1. 按照文档获取appid、api key、secret key,进行access token(用户身份验证和授权的凭证)的生成

const getbaidutoken = function () {
 return new promise((resolve, reject) => {
  //自行获取apikey、secretkey
  const apikey = apikey;
  const seckey = secretkey;
  const tokenurl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apikey}&client_secret=${seckey}`;
  wx.request({
   url: tokenurl,
   method: 'post',
   datatype: "json",
   header: {
    'content-type': 'application/json; charset=utf-8'
   },
   success: function (res) {
    resolve(res);
   },
   fail: function (res) {
    wx.hideloading();
    wx.showtoast({
     title: '网络错误,请重试!',
     icon: 'none',
     duration: 2000
    })
    reject(res);
   },
   complete: function (res) {
    resolve(res);
   }
  })
 })
}

2. 选择人脸识别-->人脸检测,人脸识别接口分为v2和v3两个版本,确认在百度云后台获得的是v2还是v3版本接口权限。

//封装识别方法
const getimgidentify = function(tokenurl, data){
 return new promise((resolve, reject) => {
  const detecturl = `https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=${tokenurl}`;
  wx.request({
   url: detecturl,
   data: data,
   method: 'post',
   datatype: "json",
   header: {
    'content-type': 'content-type:application/json; charset=utf-8'
   },
   success: function (res) {
    resolve(res);
   },
   fail: function (res) {
    wx.hideloading();
    wx.showtoast({
     title: '网络错误,请重试!',
     icon: 'none',
     duration: 2000
    })
    reject(res);
   },
   complete: function (res) {
    resolve(res);
   }
  })
 })
}

3. 调用识别方法

getbaidutoken().then((res) => {
 let token = res.data.access_token;
 let data = {
  "image": self.data.img,
  "image_type":"url",
  "face_field":"ge,beauty,expression,face_shape,gender,glasses,landmark,race,quality,eye_status,emotion,face_type"
 }
 util.getimgidentify(token, data).then((res)=>{
  //百度接口返回的结果
  let score = parseint(res.data.result.face_list[0].beauty);
  self.setdata({
   score: score,
  })
 })
})

4. 结果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网