小程序實現人臉識别功能(百度ai)
1. 按照文檔獲取AppID、API Key、Secret Key,進行Access Token(用戶身份驗證和(hé)授權的(de)憑證)的(de)生成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | const getBaiduToken = function () { return new Promise((resolve, reject) => { //自(zì)行獲取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. 選擇人臉識别-->人臉檢測,人臉識别接口分為(wèi)V2和(hé)V3兩個版本,确認在百度雲後台獲得的(de)是V2還是v3版本接口權限。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //封裝識别方法 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. 調用識别方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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)=>{ //百度接口返回的(de)結果 let score = parseInt(res.data.result.face_list[0].beauty); self.setData({ score: score, }) }) }) |
4. 結果如(rú)下:
編輯:--ns868