小程序模板網(wǎng)

小程序--人臉識(shí)別功能(百度ai)

發(fā)布時(shí)間:2018-12-26 11:19 所屬欄目:小程序開發(fā)教程

接入流程

1. 按照文檔獲取AppID、API Key、Secret Key,進(jìn)行Access Token(用戶身份驗(yàn)證和授權(quán)的憑證)的生成

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: '網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)重試!',
                    icon: 'none',
                    duration: 2000
                })
                reject(res);
            },
            complete: function (res) {
                resolve(res);
            }
        })
    })
}

2. 選擇人臉識(shí)別-->人臉檢測(cè),人臉識(shí)別接口分為V2和V3兩個(gè)版本,確認(rèn)在百度云后臺(tái)獲得的是V2還是v3版本接口權(quán)限。

//封裝識(shí)別方法
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: '網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)重試!',
                    icon: 'none',
                    duration: 2000
                })
                reject(res);
            },
            complete: function (res) {
                resolve(res);
            }
        })
    })
}

3. 調(diào)用識(shí)別方法

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)=>{
        //百度接口返回的結(jié)果
        let score = parseInt(res.data.result.face_list[0].beauty);
        self.setData({
            score: score,
        })
    })
})

4. 結(jié)果如下:

 

哼~一點(diǎn)都不準(zhǔn)


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.u-renovate.com/wxmini/doc/course/25041.html 復(fù)制鏈接 如需定制請(qǐng)聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢
AI智能客服 ×