前端调用相机组件实现人脸在线采集,通过采集到的人脸图片的base64字符串调用云开发侧实现的腾讯云人脸识别云函数,然后将识别结果回调到小程序页面中。
添加描述
添加描述
添加描述
在face云函数目录上右键选择在"在终端中打开"
E:\tencentcloudcode\wechat\functions\face>npm install
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
> protobufjs@6.8.8 postinstall E:\tencentcloudcode\wechat\functions\face\node_modules\protobufjs
> node scripts/postinstall
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN face@1.0.0 No description
npm WARN face@1.0.0 No repository field.
added 101 packages from 194 contributors and audited 186 packages in 13.832s
found 0 vulnerabilities
// 云函数入口文件
const cloud = require('wx-server-sdk') // 引入云开发服务的内核SDK
cloud.init( //初始化一个'wx-server-sdk' SDK 实例
{
env: 'ai-test-t7t64' // 开通云开发服务后创建的云环境的环境ID(默认可以创建两个ID)
}
)
// 云函数入口函数
exports.main = async (event, context) => {
const tencentcloud = require("tencentcloud-sdk-nodejs"); //引入腾讯云SDK
// 下面的代码可以通过explorer在线生成(https://console.cloud.tencent.com/api/explorer?Product=iai&Version=2018-03-01&Action=DetectFace&SignVersion=)
const IaiClient = tencentcloud.iai.v20180301.Client;
const models = tencentcloud.iai.v20180301.Models;
const Credential = tencentcloud.common.Credential;
const ClientProfile = tencentcloud.common.ClientProfile;
const HttpProfile = tencentcloud.common.HttpProfile;
let cred = new Credential("", "");
let httpProfile = new HttpProfile();
httpProfile.endpoint = "iai.tencentcloudapi.com";
let clientProfile = new ClientProfile();
clientProfile.httpProfile = httpProfile;
let client = new IaiClient(cred, "ap-guangzhou", clientProfile);
let req = new models.DetectFaceRequest();
let base64Data=event.x //接收客户端post的x参数,值类型为base64字符串
var params = {Image: base64Data, NeedFaceAttributes: 1} // 定义SDK的请求参数字典
params = JSON.stringify(params) // 转换为json字符串
req.from_json_string(params);
return new Promise((resolve, reject) => { // 通过Promise容器来接收异步API的回调,然后通过当前脚本返回给客户端
client.DetectFace(req, function(errMsg, response) { // 此接口是异步的,那么当前脚本无法对外直接访问接口返回值
if (errMsg) {
resolve({ "Result": errMsg })
}
// resp = response.to_json_string()
resolve({ "Result": response})
});
})
}
注:云函数的入口文件index.js中调用的"人脸检测与分析"API方法"DetectFace”是异步的,如果直接拷贝Explorer中生成的Demo,将无法为小程序客户端返回"DetectFace”的回调数据,脚本最终会返回null;所以这里我们需要使用Promise对象来获取"DetectFace"的回调数据,然后返回给小程序客户端
在小程序公共配置文件app.json中,添加页面生成参数
"pages/camerac/camerac",
点击"编译"生成页面目录及页面
<!--pages/camerac/camerac.wxml-->
<camera device-position="front" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
<button type="primary" bindtap="takePhoto">拍照</button>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Gender'] > 50}}">性别:男</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Gender'] < 50}}">性别:女</view>
<view>年龄:{{ FaceInfos['0']['FaceAttributesInfo']['Age'] }}</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Expression'] == 0 }}">表情:正常</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Expression'] < 50 }}">表情:微笑</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Expression'] > 50 }}">表情: 大笑</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Beauty'] == 0 }}">魅力值:一般</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Beauty'] < 50 }}">魅力值:有点迷人</view>
<view wx:if="{{ FaceInfos['0']['FaceAttributesInfo']['Beauty'] > 50 }}">魅力值:偶像级</view>
<view>请求的图片宽度:{{ ImageWidth }}</view>
<view>请求的图片高度:{{ ImageHeight }}</view>
<view>人脸框左上角横坐标:{{ FaceInfos['0']['X'] }}</view>
<view>人脸框左上角纵坐标:{{ FaceInfos['0']['Y'] }}</view>
<view>人脸框宽度:{{ FaceInfos['0']['Width'] }}</view>
<view>人脸框高度:{{ FaceInfos['0']['Height'] }}</view>
<image mode="widthFix" src="{{src}}"></image>
使用的组件:
使用的视图容器:
使用的XML语法:
使用的视图层:
// pages/camerac/camerac.js
Page({
takePhoto() { // 定义绑定的事件处理函数
var that=this; // 指定this到that,避免绑定的对象改变
const ctx = wx.createCameraContext() // 创建 camera 上下文 CameraContext 对象
ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
src: res.tempImagePath
})
var base64=wx.getFileSystemManager().readFileSync(res.tempImagePath, 'base64')
wx.cloud.init()
wx.cloud.callFunction({
// 云函数名称
name: 'face',
// 传给云函数的参数
data: {
x:base64 // 传图片的base64字符串
},
success: function(res) {
that.setData({
ImageWidth: res.result.Result.ImageWidth+"px",
ImageHeight: res.result.Result.ImageHeight+"px",
FaceInfos: res.result.Result.FaceInfos,
})
},
fail: console.error
})
}
})
},
error(e) {
console.log(e.detail)
}
})
使用到的知识点: Page 构造器
创建 camera 上下文 CameraContext 对象
注意:如果自定义函数中嵌套了wx等对象函数,数据传递应该先声明"var that=this",然后再嵌套函数,如wx.request中使用"that.setData"来传递数据
{
"navigationBarTitleText": "云开发人脸识别在线测试",
"backgroundColor": "#eeeeee"
}
/* pages/camerac/camerac.wxss */
.photo {
display: flex;
margin-top: 10px;
height: 100px;
}
.ph {
border: 1px dashed #909090;
margin-right: 30px;
width: 80px;
height: 60px;
}
.phzz {
border: 1px dashed #909090;
margin-right: 70px;
margin-left: 70px;
width: 100px;
height: 60px;
}
.phright{
border: 1px dashed #909090;
margin-left: 20px;
width: 80px;
height: 60px;
}
.textp{
margin-left: 70px;
font-size: 14px;
}
.text{
margin-left: 25px;
font-size: 14px;
}
.text2{
margin-left: 80px;
font-size: 14px;
}
.text3{
margin-left: 98px;
font-size: 14px;
}
测试效果
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。