天天看點

微信小程式人臉識别示例代碼

示例一:

1:在wxml檔案中添加一個圖檔控件和一個按鈕控件:

<button bindtap="detectFace">人臉識别</button>
<image src="{{imagePath}}" />           

2:在js檔案中添加人臉識别函數,并使用騰訊雲API實作:

const appid = 'XXXXXXXX'; // 替換成自己的騰訊雲API AppId
const secretId = 'XXXXXXXX'; // 替換成自己的騰訊雲API SecretId
const secretKey = 'XXXXXXXX'; // 替換成自己的騰訊雲API SecretKey
const region = 'ap-guangzhou'; // 替換成自己的騰訊雲API Region
const url = 'https://iai.tencentcloudapi.com/';

Page({
  data: {
    imagePath: ""
  },
  detectFace: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        const imagePath = res.tempFilePaths[0];
        this.setData({
          imagePath: imagePath
        });
        wx.showLoading({
          title: "正在識别人臉"
        });
        wx.uploadFile({
          url: url,
          filePath: imagePath,
          name: "image",
          formData: {
            Action: "DetectFace",
            Version: "2018-03-01",
            Region: region,
            Timestamp: parseInt(new Date().getTime() / 1000),
            Nonce: Math.round(Math.random() * 65535),
            SecretId: secretId,
            ImageUrl: "",
            MaxFaceNum: 1,
            NeedFaceAttributes: 1,
            FaceAttributesType: [
              "Age", "Gender", "Expression", "Beauty"
            ]
          },
          header: {
            "Content-Type": "multipart/form-data"
          },
          success: (res) => {
            wx.hideLoading();
            const result = JSON.parse(res.data);
            if (result.Response.Error) {
              wx.showToast({
                title: result.Response.Error.Message,
                icon: "none"
              });
            } else {
              const face = result.Response.FaceInfos[0];
              const age = face.FaceAttributesInfo.Age;
              const gender = face.FaceAttributesInfo.Gender;
              const expression = face.FaceAttributesInfo.Expression;
              const beauty = face.FaceAttributesInfo.Beauty;
              wx.showModal({
                title: "識别結果",
                content: "年齡:" + age + "\n" +
                  "性别:" + gender + "\n" +
                  "表情:" + expression + "\n" +
                  "顔值:" + beauty,
                showCancel: false
              });
            }
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: "識别人臉失敗",
              icon: "none"
            });
          }
        });
      }
    });
  }
})
           

該代碼使用wx.chooseImage函數從本地相冊或攝像頭選擇一張照片,然後使用wx.uploadFile函數将照片上傳到騰訊雲API。

示例二:

1:在wxml檔案中添加一個圖檔控件和一個按鈕:

<button bindtap="detectFace">識别人臉</button>
<image src="{{imageUrl}}" mode="aspectFit"></image>           

2:在js檔案中添加上傳圖檔和識别人臉的函數:

Page({
  data: {
    imageUrl: ""
  },
  detectFace: function() {
    wx.chooseImage({
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: "上傳中",
        });
        wx.uploadFile({
          url: "https://api-cn.faceplusplus.com/facepp/v3/detect",
          filePath: tempFilePaths[0],
          name: "image_file",
          formData: {
            api_key: "YOUR_API_KEY",
            api_secret: "YOUR_API_SECRET",
            return_landmark: 1,
            return_attributes: "gender,age"
          },
          success: (res) => {
            wx.hideLoading();
            var data = JSON.parse(res.data);
            if (data.faces && data.faces.length > 0) {
              this.setData({
                imageUrl: tempFilePaths[0]
              });
              wx.showToast({
                title: "識别成功",
                icon: "success"
              });
            } else {
              wx.showToast({
                title: "未檢測到人臉",
                icon: "none"
              });
            }
          },
          fail: () => {
            wx.hideLoading();
            wx.showToast({
              title: "上傳失敗",
              icon: "none"
            });
          }
        });
      }
    });
  }
})
           

該代碼使用wx.chooseImage函數選擇圖檔并上傳到Face++ API,使用formData參數指定API Key、API Secret、傳回的人臉關鍵點和屬性。然後解析傳回的JSON資料,如果檢測到人臉,将圖檔位址綁定到頁面資料的imageUrl屬性上,并使用wx.showToast函數彈出識别成功的提示資訊。如果未檢測到人臉,彈出未檢測到人臉的提示資訊。當上傳圖檔失敗時,使用wx.showToast函數彈出上傳失敗的提示資訊。

請注意,Face++ API需要申請賬号并擷取API Key和API Secret才能使用。