欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三分钟让你实现人脸对比_nodejs_人脸识别技术

程序员文章站 2022-07-12 20:08:49
...

三分钟让你实现人脸对比_nodejs_人脸识别技术

注册百度云账号丶获取APP key 丶Secret key

  1. 首先注册百度开发者账号。登录-控制台-人脸识别-创建应用
    三分钟让你实现人脸对比_nodejs_人脸识别技术
  2. 确认创建
    三分钟让你实现人脸对比_nodejs_人脸识别技术
    3丶人脸识别-应用管理
    三分钟让你实现人脸对比_nodejs_人脸识别技术

nodejs后台

api文档 地址
1丶获取 access_token
想要调用 人脸识别接口 。必须要通过你的 appkey和Secret key来获取access_token。它是调用人脸识别接口的必要参数。并且注意30天需要更换一次access_token

var https = require('https');
var qs = require('querystring');
var CLIENTID='********';//App key
var CLIENTSECRET='********';//Secret key
const param = qs.stringify({
    'grant_type': 'client_credentials',
    'client_id': CLIENTID,
    'client_secret': CLIENTSECRET
});
async function  getAccess_token(){
    await new Promise((resolve,reject)=>{
        https.get(
            {
                hostname: 'aip.baidubce.com',
                path: '/oauth/2.0/token?' + param,
                agent: false
            },
            function (res) {
                // 在标准输出中查看运行结果
                //res.pipe(process.stdout);
                res.on('data', (d) => {
                    reject({
                        code:0,
                        msg:'success',
                        data:JSON.parse(d.toString()).access_token
                    })
                });
            }
        ).on('error', (e) => {
            resolve({
                code:1,
                msg:'network error',
                info:e,
                data:JSON.parse(d.toString()).access_token
            })
        });
    })
}
getAccess_token().then(data=>{
    console.log(data);//access_token
}).catch(err=>{
    console.log(err)
})

2丶人脸对比识别 胡乱写的

人脸对比识别 请求接口 https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=您的access_token

var person="https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="+"您的access_token";
var axios = require('axios');
var https = require('https');
var fs=require('fs');
function img1(){
    return "去掉头部信息base64图片";
}
async function matchPerson(personVerifyImg,personContrast=img1()){
	//参数文档里面有详解。我这里就不写了
    const param = [
        {
            "image": personVerifyImg,
            "image_type": "BASE64",
            "face_type": "LIVE",
            "quality_control": "NORMAL",
            "liveness_control": "HIGH"
        },
        {
            "image": personContrast,
            "image_type": "BASE64",
            "face_type": "IDCARD",
            "quality_control": "NORMAL",
            "liveness_control": "NORMAL"
        }
        
    ];
    return new Promise((reslove,reject)=>{
        axios(
            {
                url:person,
                method:"post",
                header:{
                    "Content-Type":"application/json"
                },
                data:param
            },
        ).then(data=>{
            reslove(data.data)
        }).catch(err=>{
            reject(err)
        }); 
    })
    
}
const Koa = require('koa');
const router = require('koa-router')();
var bodyParser = require('koa-bodyparser')
const app = new Koa();
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*');
    await next();
});
app.use(async (ctx, next)=> {
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
      ctx.body = 200; 
    } else {
      await next();
    }
});
//配置post bodyparser的中间件
app.use(bodyParser());
router.post('/gaga', async (ctx, next) => {
    try{
        await matchPerson(ctx.request.body.imgSrc).then(data=>{
            ctx.response.body=data
        }).catch(err=>{
            ctx.response.body=err
        })
    }catch(err){
        ctx.response.body=err
    }
});

app.use(router.routes());
app.use(router.allowedMethods());
app.use(async ctx => {
  ctx.body = 'Hello World';
});
//ssl证书。我这里使用的腾讯云
var options = {
    key:fs.readFileSync('./images/www.flycdp.com/Nginx/2_www.flycdp.com.key'), 
    cert: fs.readFileSync('./images/www.flycdp.com/Nginx/1_www.flycdp.com_bundle.crt'),
};
https.createServer(options, app.callback()).listen(3000,function(){
    console.log('https://127.0.0.1:3000')
});

js前端

获取摄像头权限(需https环境)


<!doctype html>
<html lang="en">
<head>
    <title>GET VIDEO</title>
    <meta charset="utf-8">
    <style>
        canvas{
            display: none;
        }
        img{
            display: none;
        }
    </style>
    <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
</head>
<body>
<input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia()" />
<div style="margin: 0 auto; text-align: center;">
    <video id="video" width="500px" height="500px" autoplay="autoplay" muted></video>
</div>
<canvas id="canvas" width="150px" height="150px"></canvas>
<button id="snap" onclick="takePhoto()">拍照</button>
<script>
    //获得video摄像头区域
    var video = document.getElementById("video");
    function getMedia() {
        var constraints = {
            video: {width: 500, height: 500},
            audio: true
        };
        var promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(function (MediaStream) {
            video.srcObject = MediaStream;
            video.play();
        }).catch(function (PermissionDeniedError) {
            console.log(PermissionDeniedError);
        })
    }
    function takePhoto(myCanvas) {
        //获得Canvas对象
        var myCanvas = document.getElementById("canvas");
        var ctx = myCanvas.getContext('2d');
        ctx.drawImage(video, 0, 0, 150, 150);//video转canvas。相当于拍照功能
        convertImageToBase64(myCanvas,ctx);
    }
    function base64CutHeader(base64Str){
        return base64Str.substring(base64Str.indexOf(",")+1);
    }
    function convertImageToBase64(myCanvas,ctx) {
        var src = myCanvas.toDataURL("image/jpeg", 0.5);//canvas转base64
        var dataStr=base64CutHeader(src);//去掉base64的头部信息
        /* 把src上传给服务器。如果服务器验证成功则返回 */
        try{
            axios({
            method:"post",
            data:{
                imgSrc:dataStr
            },
            url:"https://192.168.0.176:3000/gaga",

            }).then(data=>{
                if(data.data.error_code==0){
                    if(data.data.result.score>=85){//百度推荐的80.我这里判断相似度大于等于85%为同一人
                        alert(`相似度${data.data.result.score} 是晨的皮大大`);
                        return ;
                    }else{
                        alert(`相似度${data.data.result.score} 不是晨的皮大大`);
                    }
                }else{
                    alert("不允许是手机翻盘照片")
                }
                
            }).catch(err=>{
                alert(err)
            })
        }catch(err){
            console.log(err)
        }
    }
</script>
</body>

相关标签: 人脸识别 nodejs