本人,小白一个,大神可忽略本内容
由于uniapp,在打包成APP的时候不能自定义相机,很多人脸识别的项目,在APP里面只能使用原生,本人也不会原生,很是苦逼,很羡慕能开发原生的,但是也想搞一下人脸识别,迫于无奈,研究属于自己的一套,h5的人脸识别,喜欢的可以研究研究。
自定义相机启动界面
自定义摄像头界面大小,遮罩等
人脸放到框内,自动拍照,保存base64,也快手动拍照
识别到人脸以后,大家可以自行发挥了,如,人脸对比等...
<script>
//激活摄像头
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getUserMedia({video:true}, gotStream, noStream);
function gotStream(stream) {
myVideo.src = URL.createObjectURL(stream);
myVideo.onerror = function () {
stream.stop();
};
stream.onended = noStream;
myVideo.onloadedmetadata = function () {
console.log('摄像头成功打开!');
};
}
function noStream(err){
console.log(err);
}
//激活摄像头end
var saveArray = {};
window.onload = function () {
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var tracker = new tracking.ObjectTracker('face');
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);
tracking.track('#video', tracker, {camera: true});
tracker.on('track', function (event) {
context.clearRect(0, 0, canvas.width, canvas.height);
event.data.forEach(function (rect) {
context.strokeStyle = '#fff';
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
//context.font = '11px Helvetica';
context.fillStyle = "#fff";
context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
saveArray.x = rect.x;
saveArray.y = rect.y;
saveArray.width = rect.width;
saveArray.height = rect.height;
});
});
setInterval(function () {
//console.log(saveArray);
if (saveArray.x > 80 &&
saveArray.x + saveArray.width < 260 &&
saveArray.y > 90 &&
saveArray.y + saveArray.height < 260 &&
saveArray.width < 150
&& saveArray.height < 150) {
console.log(saveArray);
getPhoto();
for (var key in saveArray) {
delete saveArray[key];
}
}
}, 2000);
function getPhoto() {
context2.drawImage(video, 100, 120, 260, 380, 0, 0, 170, 255); //将video对象内指定的区域捕捉绘制到画布上指定的区域,实现拍照。
}
var btn = document.getElementById("btn");
btn.onclick= function () {
getPhoto();
}
var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d');
var can = document.getElementById('shortCut');
var context2 = can.getContext('2d');
context1.strokeStyle = "#69fff1";
context1.moveTo(63, 66); //上线 x,y
context1.lineTo(257, 66); //右
context1.lineTo(257, 321); //下
context1.lineTo(63, 321);//左
context1.lineTo(63, 66);//左
context1.stroke();
var img = document.getElementById("img")
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
var keepImg = document.getElementById("keepImg");
keepImg.onclick = function () {
var photoImg = document.createElement("img");
photoImg.src = convertCanvasToImage(can).src;
img.appendChild(photoImg);
console.log(convertCanvasToImage(can).src);
}
};
</script>