天天看点

微信小程序人脸识别示例代码

示例一:

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才能使用。