<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>利用facedetection插件,实现JQuery+PHP的图像人脸识别</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="jquery.facedetection.min.js"></script>
</head>
<body>
<style>
/*识别到人脸后,进行画框标记的方框样式*/
.findface {
border: 2px solid #ff0000;
left: -1000px;
position: absolute;
top: -1000px;
}
</style>
<div class="imgContainer">
<img id="picture" src="" />
</div>
<script>
/*
facedetection人脸识别结果,返回找到对象的数组说明:
x —图片中脸部的X坐标
y-图片中人脸的Y坐标
width —脸的宽度
高度 -脸部高度
positionX —相对于文档的X位置
positionY —相对于文档的Y位置
offsetX —相对于偏移父级的X位置
offsetY —相对于偏移父级的Y位置
scaleX —原始图像宽度和显示宽度之间的比率
scaleY —原始图像高度和显示高度之间的比率
confidence - 信心水平
——————————————————————————————————————————————————————————
console.log值:
0:
confidence: 0.53963825
height: 96.50000000000009
neighbors: 1
offsetX: 136.5000000000001
offsetY: 104.50000000000009
positionX: 136.5000000000001
positionY: 104.50000000000009
scaleX: 1
scaleY: 1
width: 96.50000000000009
x: 128.5000000000001
y: 96.50000000000009
——————————————————————————————————————————————————————————
参数设定值
interval —时间间隔(默认为4)
minNeighbors —最小邻居阈值,用于设置将矩形组作为面丢弃的截止级别(默认为1)
confidence -置信度 -最小置信度(默认为null)
async —异步模式(如果Worker可用)(默认为false)。异步模式使用Workers,并且需要脚本位于同一域中。
grayscale —灰度 —处理前转换为灰度(默认为true)
complete —检测完成后触发的回调函数
complete: function (faces) {
// ...
}
error —触发了错误的回调函数
error: function (code, message) {
// ...
}
*/
var xhr = new XMLHttpRequest();
xhr.open("get", 'uploads/a.jpg', true);
//人脸无法识别图片
// xhr.open("get", 'uploads/b.jpg', true);
xhr.responseType = "blob";
xhr.onload = function(){
if(this.status == 200){
//得到一个blob对象
var blob = this.response;
console.log("blob", blob)
// 至关重要
let oFileReader = new FileReader();
oFileReader.onloadend = function(e){
// 此处拿到的已经是base64的图片了,可以赋值做相应的处理
console.log(e.target.result)
$('#picture').attr('src',e.target.result);
}
oFileReader.readAsDataURL(blob);
}
}
xhr.send();
setTimeout(()=>{
var img = document.getElementById('picture');
//画方框
function draw(x, y, w, h) {
var findface = document.createElement('div');
document.querySelector('.imgContainer').appendChild(findface);
findface.classList.add('findface');
findface.style.width = w + 'px';
findface.style.height = h + 'px';
findface.style.left = (img.offsetLeft + x) + 'px';
findface.style.top = (img.offsetTop + y) + 'px';
};
//对图像中人脸的识别
$('#picture').faceDetection({
//confidence:3,//置信度设置,0.1至1之间,值越大要求越匹配度越严格
complete: function (faces) {
if (faces.length == 0) { //说明没有检测到人脸
alert("无人脸")
} else {
console.log(faces);//输出识别到的人脸数据
for (var i in faces) {
//将多个被识别到的人脸图像进行画框标记
draw(faces[i].x, faces[i].y, faces[i].width, faces[i].height);
}
}
}
});
},1000);
</script>
</body>
</html>