百度AI 人臉識別 v3 node版
阿新 • • 發佈:2019-02-20
/*
從前臺到後臺的人臉識別
1.開啟攝像頭
1)window.navigator
2.同步到video的src
物件=> window.URL =>blob
1)解析視訊流為blob 新增到 src
3.canvas建立視訊片段照片
4.
*/
var open = document.querySelector('.open');//獲取open按鈕
var capture = document.querySelector('.capture'); // 獲取video標籤
var recognition = document.querySelector('.recognition'); //獲取人臉識別的按鈕
var close = document.querySelector('.close');
var notice = document.querySelector('.notice');
var canvas = document.querySelector('.draw_img');
var context = canvas.getContext('2d' );
var buffer;
open.onclick = invokingCamera; //回撥函式 函式名稱加括號是主動執行
recognition.onclick = screenShot; //點選人臉識別
close.onclick = function () {
//console.log(buffer);
buffer && buffer.getTracks()[0].stop(); //停止視訊流
//console.log(buffer);
}
//獲取攝像頭,獲取流媒體資料
function invokingCamera() {
if (navigator.mediaDevices.getUserMedia) {
//優先使用前置攝像頭
navigator.mediaDevices.getUserMedia({audio: false, video: {facingMode: "user"}}).then(
//獲取視訊流資料 成功後
function (MediaStream) {
//console.log(stream);
buffer = MediaStream; //會指向一個記憶體地址
//console.log(buffer);
capture.srcObject = MediaStream;
capture.onloadedmetadata = function(e) {
capture.play();
};
}
).catch(
//失敗後
function (err) {
console.log(err.name + ": " + err.message);
}
);
} else {
alert('您的瀏覽器不支援攝像頭');
}
}
function screenShot() {
msg('正在檢測,請稍後~~~', '#c665ff');
context.drawImage(capture,0,0,200,150);
new Post({
url: '/judge',
data:canvas.toDataURL('image/png'),
success: function (res) {
console.log(res); //伺服器傳送的訊息
res = JSON.parse(res).result.score;
console.log(typeof res);
if (res > 85) {
msg('歡迎主人~', '#7ef6c7');
} else {
msg('醜拒~~', '#f10d0f');
}
}
})
}
function msg(con, color) { //輸出資訊
notice.innerHTML = con + '';
notice.style.color = color;
}
//post 方式傳輸資料 get的話 base64 5mb url
function Post(opt) {
//建構函式
this.init(opt);
}
Post.prototype = {
init: function (opt) { //初始化 引數 URL地址 Data引數 method方式
this.url = opt.url || '';
this.data = opt.data || {};
this.method = 'POST';
this.async = true;//非同步
this.success = opt.success || function () { //回撥函式
}
this.xhr();
},
xhr: function () {
var that = this;
var xhr = new XMLHttpRequest();//ajax物件例項化
console.log(this.data)
//請求的型別 請求地址 非同步或者同步
xhr.open(this.method, this.url, this.async);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); //表頭
xhr.send('img='+this.data);
xhr.onreadystatechange = function (ev) {
if (xhr.status === 200 && xhr.readyState === 4) {
this.success(xhr.response);//回撥資料
}
}.bind(this);
}
}
new Post({
url: '/access',
data:'',
})