小程序实现人脸检测
先简单介绍一下我们实现的功能,我们通过微信小程序调用百度人脸检测接口,当人脸在屏幕适当的位置,界面上的图案会变成绿色,然后会提示是上传成功的字样。
第一步我们需要注册百度api人脸识别接口,然后编写以下代码。
face.js
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
imgsrc:"../common/jpg/scan_ing.png",
src:"",
windowWidth: 0,
windowHeight:0,
trackshow: "进行人脸追踪",
canvasshow:true,
access_token:''
},
onLoad() {
var that = this
wx.showLoading({
title: '努力加载中',
mask: true
})
//屏幕宽度
var sysInfo = wx.getSystemInfoSync()
that.setData({
windowWidth: sysInfo.windowWidth,
windowHeight: sysInfo.windowHeight,
})
that.ctx = wx.createCameraContext()
// 每次更新access_token
wx.request({
url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + app.globalData.baidukey + "&client_secret=" + app.globalData.baidusecretkey,
method: 'POST',
dataType: "json",
header: {
'content-type': 'application/json'
},
success: function (res) {
// console.log(res.data.access_token);
// app.globalData.access_token = res.data.access_token;
that.setData({
access_token: res.data.access_token
});
}
})
//打印access_token
console.log(app.access_token);
wx.hideLoading()
var that =this
that.setData({
trackshow: "停止人脸追踪",
canvasshow: true
})
that.takePhoto()
that.interval = setInterval(this.takePhoto, 500);
},
takePhoto() {
console.log("takePhoto")
var that = this
var takephonewidth
var takephoneheight
that.ctx.takePhoto({
quality: 'low',
success: (res) => {
// console.log(res.tempImagePath),
// 获取图片真实宽高
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 => { //成功的回调
// 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:1
},
method: 'POST',
dataType: "json",
header: {
'content-type': 'application/json' },
success: function (res) {
console.log(res.data);
if (res.data.error_code === 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.windowHeight
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.windowHeight
ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
}
// wx.drawCanvas({
// canvasId: 'canvas',
// actions: ctx.getActions()
// })
var x1 = res.data.result.face_list[0].location.left / takephonewidth * that.data.windowWidth;
var y1 = res.data.result.face_list[0].location.top / takephoneheight * that.data.windowHeight;
var sw = (res.data.result.face_list[0].location.width / takephonewidth * that.data.windowWidth);
var sh = (res.data.result.face_list[0].location.height / takephoneheight * that.data.windowHeight);
var centerX = x1+sw*0.5;
var centerY = y1+sh*0.5;
var screenX = that.data.windowWidth * 0.5;
var screenY = that.data.windowHeight * 0.5;
//左右角度
var x = res.data.result.face_list[0].angle.yaw;
//俯仰角度
var y = res.data.result.face_list[0].angle.pitch;
if(((x>=-12.0&&x<=12.0)&&(y>=-8.0&&y<=15.0)&&(sw<=that.data.windowWidth*0.5&&sh<=that.data.windowHeight*0.5))
&&(((centerX>=screenX-20.0)&&(centerX<=screenX+20.0))&&(centerY>=screenY-80.0)&&(centerY<=screenY+80.0))){
that.setData({
imgsrc:"../common/jpg/scan_sucess.png",
});
that.upload();
} else{
that.setData({
imgsrc:"../common/jpg/scan_ing.png",
});
}
var ctx = wx.createContext()
ctx.setStrokeStyle('#31859c')
ctx.lineWidth = 3
// wx.drawCanvas({
// canvasId: 'canvas',
// actions: ctx.getActions()
// })
}else{
that.setData({
imgsrc:"../common/jpg/scan_ing.png",
});
}
},
})
}
})
}
})
},
upload(){
console.log('上传照片');
var that = this;
clearInterval(that.interval);
wx.showLoading({
title: '上传中',
})
setTimeout(function () {
wx.hideLoading()
//还需添加上传到服务器的代码
wx.showToast({
title: '上传成功',
icon: 'success',
duration: 2000,
success:function(){
wx.reLaunch({
url: '../index/index',
})
}
})
}, 2000)
},
onUnload:function(){
var that = this
clearInterval(that.interval)
},
})
上面的图片
识别成功:
识别失败
face.wxml
<!--face.wxml-->
<view class="page-body">
<view class="page-body-wrapper">
<camera device-position="front" flash="off" binderror="error" style="width:100%;height:{{windowHeight}}px;">
<cover-view style="display: flex;align-items: center;justify-content: center; width: 100%;height:{{windowHeight}}px;">
<cover-image class="cover-img-view" src="{{imgsrc}}" style="width:90%;height:{{windowHeight*0.8}}px;"/>
</cover-view>
</camera>
<canvas wx:if="{{canvasshow}}" style="width: 100%;height:{{windowHeight}}px;position:absolute;" canvas-id="canvas"></canvas>
</view>
</view>
face.wxml
/**face.wxss**/
.preview-tips {
margin: 50rpx 0 30rpx;
}
.video {
margin: 20rpx auto;
width: 100%;
height: 300px;
}
page {
background-color: #F6F8F8;
height: 100%;
font-size: 32rpx;
line-height: 1.6;
}
/* .page-body {
padding: 20rpx 0;
} */
.page-body-wrapper {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.btn-area {
margin-top: 40rpx;
box-sizing: border-box;
width: 100%;
padding: 0 30rpx;
}
Tips: 如果想要显示脸的识别框,可以把上面代码的所有注释语句都取消注释就可以了