最近接到一个项目微信小程序调用百度api进行人脸识别 废话吧不多说 直接上代码
1.首先先在百度申请api 做人脸识别
这里是我的请求封装
//封装post get
function $http(url, method, param = {}, lookup) {
//url 地址
//method 传参方式
//param 接受的值 get 可传空
//lookup 因为公司查询的时候需要传时间戳 通过lookup判断是否需要传输时间戳
// var newdata = new Date().getTime();
var baseUrl = `${url}`;
console.log(param)
var params = Object.assign(param);
// console.log(baseUrl,params)
switch (method) {
case 'get':
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl,
data: params,
method:'get',
success(res) {
resolve(res.data)
},
fail(err){
console.log(err)
}
})
});
break;
case 'post':
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl,
data: params,
method: 'post',
dataType:'json',
headers: {
"Content-Type": "application/json" //设置跨域头部
},
success(res) {
resolve(res.data)
},
fail(err) {
console.log(err)
}
})
});
break;
}
}
module.exports={
$http: $http
}
2.首先通过小程序 camera 创建相机
<camera mode=" " device-position="front" flash="auto" binderror="error" class="sxt">
</camera>
3.逻辑代码加人脸追踪
var http = require('../../utils/http.js');
var app = getApp();
Page({
data: {
srcimg: '',
src: "",
// fengmian: "",
// videoSrc: "",
// who: "",
openid: "",
token: "",
windowWidth: '',
// trackshow: "进行人脸追踪",
canvasshow: true,
access_token: '',
facesrc: '',
faceimg: '',
//手机号
phoneNumber:'',
//判断手机号
phoneType:false,
phoneTypeFopur:true,
//相似数组
faceListPage:[],
//公众号openid
openId:'',
//高度
windowheight:'100',
bigWidth:'',
//轮播图是否显示
lunbo:false,
lunboheight:'',
phonemargin:'110',
topsxt:''
},
onLoad() {
var that = this
var query = wx.createSelectorQuery();
//选择id
//获取某个view宽度
query.select('.face').boundingClientRect(function (rect) {
that.setData({
windowWidth: rect.height
})
}).exec();
wx.showLoading({
title: '努力加载中',
mask: true
})
//屏幕宽度
var sysInfo = wx.getSystemInfoSync();
that.ctx = wx.createCameraContext();
console.log(that.ctx)
// console.log("onLoad"),
that.setData({
openid: app.globalData.openid,
token: app.globalData.token
});
//每次更新tooken
http.$http("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + 'QyMGdRjCkMyrGXyaIN482x7b' + "&client_secret=" + 'ba0gjxKjKuu6I7vZqSKqvK26Z3N47QvD', "get", "")
.then(res => {
// this.userList = res.data;
// console.log(res)
wx.hideLoading();
this.setData({
access_token: res.access_token
});
})
.catch(err => { });
wx.hideLoading()
//判断是什么手机
// console.log(app.phone())
that.setData({
phonemargin: app.phone().phonemargin,
topsxt: app.phone().topsxt
})
},
onShow(){
//获取全部宽度
let that = this
that.setData({
windowheight: app.heightNum().windowheight,
lunbo: app.heightNum().lunbo,
lunboheight: app.heightNum().lunboheight,
})
},
onReady: function () {
let that = this;
let interval = setInterval(that.takePhoto,1500)
},
takePhoto() {
// console.log("takePhoto")
var that = this
var takephonewidth
var takephoneheight
that.ctx.takePhoto({
quality: 'low',
success: (res) => {
// console.log(res),
// 获取图片真实宽高
wx.getImageInfo({
src: res.tempImagePath,
success: function (res) {
takephonewidth = res.width,
takephoneheight = res.height
}
})
// console.log(takephonewidth, takephoneheight)
wx.getFileSystemManager().readFile({
filePath: res.tempImagePath, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
this.setData({
facesrc: res.tempImagePath,
faceimg: res.data
})
// console.log('data:image/png;base64,' + res.data)
//调用活体验证的方法
wx.request({
url: "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + that.data.access_token,
data: {
image: res.data,
image_type: "BASE64",
max_face_num: 10,
face_field:'quality,landmark,beauty,face_type'
},
method: 'POST',
dataType: "json",
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log(res)
// console.log(res.data);
//canvas 绘制
if (res.data.error_code === 0 && res.data.result.face_list[0].quality.completeness!=0) {
var ctx = wx.createContext()
ctx.setStrokeStyle('#31859c')
ctx.lineWidth = 3
for (let j = 0; j < res.data.result.face_num; j++) {
var cavansl = res.data.result.face_list[j].location.left / takephonewidth * that.data.windowWidth
var cavanst = res.data.result.face_list[j].location.top / takephoneheight * that.data.windowWidth
var cavansw = res.data.result.face_list[j].location.width / takephonewidth * that.data.windowWidth
var cavansh = res.data.result.face_list[j].location.height / takephoneheight * that.data.windowWidth
ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
}
wx.drawCanvas({
canvasId: 'canvas',
actions: ctx.getActions()
})
that.FaceImgLookup();
} else {
var ctx = wx.createContext()
ctx.setStrokeStyle('#31859c')
ctx.lineWidth = 3
wx.drawCanvas({
canvasId: 'canvas',
actions: ctx.getActions()
})
}
},
})
}
})
}
})
},
//在人脸库中查找是否有这个人脸
FaceImgLookup() {
let that = this;
http.$http("https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + that.data.access_token, 'post', {
image: that.data.faceimg,
image_type: 'BASE64',
group_id_list: 'faceImg',
liveness_control: 'HIGH',
max_user_num:'5',
}).then(res => {
console.log(res);
if (res.error_code == 0) {
if (res.result.user_list[0].score > 80 && res.result.user_list.length == 1) {
console.log('人脸库中有这个人');
return
} else if (res.result.user_list[0].score > 80&&res.result.user_list.length>1){
that.setData({
faceListPage:res.result.user_list
})
console.log('人脸库中有这个人,并且还有几个相似的', that.data.faceListPage);
return
}else {
console.log('人脸库中没有这个人');
that.addFaceImg();
return
}
} else if (res.error_code == 222207) {
console.log('空的人脸库我要去添加');
that.addFaceImg();
return
} else if (res.error_code == 223120) {
console.log('活体验证未通过')
}
})
.catch(err => {
console.log(err)
})
},
//人脸id
faceId() {
var outTradeNo = ""; //人脸id
for (var i = 0; i < 6; i++) //6位随机数,用以加在时间戳后面。
{
outTradeNo += Math.floor(Math.random() * 10);
}
return new Date().getTime() + outTradeNo; //时间戳,用来生成id号
},
// 调用储存人脸的方法
addFaceImg() {
let that = this;
http.$http("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + that.data.access_token, 'post', {
image: that.data.faceimg,
image_type: 'BASE64',
group_id: 'faceImg',
user_id: that.faceId()
}).then(res => {
// this.userList = res.data;
console.log(res);
if (res.error_code == 0) {
console.log('人脸储存成功')
}
})
.catch(err => {
console.log(err)
})
},
onUnload: function () {
var that = this
// clearInterval(that.interval)
},
error(e) {
console.log(e.detail)
}
})