展示
界面展示
正下方三个按钮:
左边:切换前后置摄像头
中间:拍照
右边:选择相册
识别结果展示
图像中有人脸时显示识别结果:
图像中无人脸时不显示识别结果:
获取百度智能云人脸识别API
1.进入百度智能云官网,注册账号并登录
2.进入用户中心后,如图所示依次点击产品服务
-人脸识别
3.之后再如图所示依次点击应用列表
-马上创建
4.根据流程创建新应用即可
5.创建完成后回到应用列表界面即可看见API Key
与Secret Key
(这两串字符是我们微信小程序前端与百度API交互的关键)
微信小程序端
主要代码:
代码中有两个URL
。分别是获取token
与请求检测
getFaceInfo() {
// 获取token
wx.request({
method: 'POST',
url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=123456789&client_secret=123456789',
success: (res) => {
// 为 token 赋值
this.setData({
token: res.data.access_token
}, () => {
this.processParams()
})
}
})
},
client_id=
后替换成自己申请的API Key;
client_secret=
后替换成相应的Secret Key
// 请求检测
testFace(params) {
wx.showLoading({
title: '表情检测中...',
})
wx.request({
// 请求的类型
method: 'POST',
// 请求的地址
url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + this.data.token,
// 请求头
header: {
'Content-Type': 'application/json'
},
// 请求体
data: params,
// 成功的回调函数
success: (res) => {
if (res.errMsg === 'request:ok' && res.data.result !== null && res.data.result.face_num !== 0) {
this.setData({
faceinfo: res.data.result.face_list[0]
})
}
},
complete: () => {
wx.hideLoading()
}
})
}
})
代码中需要注意的是上述两个
url地址
可能会因百度官方的调整而发生变化。因此需要我们学会看百度官方的开发文档。
1.如图所示,点击技术文档后即可查看。
2.选择人脸识别,再点击Access Token获取
即可查看最新的授权服务地址
如图所示即为最新的授权服务地址
同理,文档也有请求检测的最新URL地址