SpringBoot integrates Baidu AI to realize face recognition


Face recognition login is now used in many scenarios, such as APP login, face recognition at gates, and so on. This article is to study about face recognition. The executable source code is attached at the end of the article. The open platform chosen is Baidu AI. Of course, other options are also available.

1. Baidu AI Open Platform

To choose Baidu AI, of course, you have to create the corresponding account and create application information at the same time.

Enter the Baidu AI official website, then select the face and human body in the open ability Tab, and operate as shown in the figure.

insert image description here

insert image description here

Just log in when you should log in, Baidu account.

insert image description here

For new users, you can choose to try it out for free, or you have to recharge, if you practice your hands, this is enough, anyway, you can get it for free.

After receiving it, you need to create a test application and generate three important pieces of information: AppID, API Key,Secret Key

insert image description here

2. Document Integration

After creating the application information, you can integrate the SDK, which contains various languages: Android, IOS, Java, PHPetc., integrated in this article Java HTTP SDK.

insert image description here

insert image description here

The documentation is actually very detailed.

3. Code implementation

The frame is used as follows: SpringBoot + JPA + MySQL. Of course JPAyou can use MybatiseitherMybatisPlus

3.1 Create a SpringBoot project

3.2 Add Baidu AI dependency

Just add the following dependencies. The version number can mavenbe found on the official website

<dependency>
    <groupId>com.baidu.aip</groupId>
    <artifactId>java-sdk</artifactId>
    <version>${version}</version>
</dependency>

3.3 Create AipFace

AipFaceIt is a face recognition Javaclient, which provides a series of interaction methods for developers using face recognition. After the initialization is complete, it is recommended to use a single instance to avoid repeated acquisition access_token(official words)

@Configuration
public class BaiduConfig {
    
    

    @Value("${baidu.appId}")
    private String appId;

    @Value("${baidu.key}")
    private String key;

    @Value("${baidu.secret}")
    private String secret;

    @Bean
    public AipFace aipFace(){
    
    
        return new AipFace(appId,key,secret);
    }
}

3.4 Register face interface

Base64 encoding of the face image uploaded by the client, and save the user's face image locally and store it in the database

@RequestMapping(value = "register",method = RequestMethod.POST)
public String register(String userName,String faceBase) throws IOException {
    
    
    if(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(faceBase)) {
    
    
        // 文件上传的地址
        System.out.println(filePath);
        // 图片名称
        String fileName = userName + System.currentTimeMillis() + ".png";
        System.out.println(filePath + "\\" + fileName);
        File file = new File(filePath + "\\" + fileName);

        // 往数据库里插入一条用户数据
        Users user = new Users();
        user.setUserName(userName);
        user.setUserPhoto(filePath + "\\" + fileName);
        Users exitUser = userService.selectUserByName(user);
        if(exitUser != null) {
    
     
            return "2";
        }
        userService.addUsers(user);

        // 保存上传摄像头捕获的图片
        saveLocalImage(faceBase, file);
        // 向百度云人脸库插入一张人脸
        faceSetAddUser(aipFace,faceBase,userName);
    }
    return "1";
}


public boolean saveLocalImage(String imgStr, File file) {
    
    
    // 图像数据为空
    if (imgStr == null) {
    
    
        return false;
    }else {
    
    
        BASE64Decoder decoder = new BASE64Decoder();
        try {
    
    
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
    
    
                if (bytes[i] < 0) {
    
    
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            if(!file.exists()) {
    
    
                file.getParentFile().mkdir();
                OutputStream out = new FileOutputStream(file);
                out.write(bytes);
                out.flush();
                out.close();
                return true;
            }

        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    } 
    return false;	
}

public boolean faceSetAddUser(AipFace client, String faceBase, String username) {
    
    
    // 参数为数据库中注册的人脸
    HashMap<String, String> options = new HashMap<String, String>();
    options.put("user_info", "user's info");
    JSONObject res = client.addUser(faceBase, "BASE64", "user_01", username, options);
    return true;
}

3.5 Face login interface

@RequestMapping(value = "login",method = RequestMethod.POST)
public String login(String faceBase) {
    
    
    String faceData = faceBase;
    // 进行人像数据对比
    Double num = checkUser(faceData,aipFace);
    if( num > 80) {
    
    
        return "1";
    }else {
    
    
        return "2";
    }
}

public Double checkUser(String imgBash64,AipFace client) {
    
    
    // 传入可选参数调用接口
    HashMap<String, String> options = new HashMap<String, String>();
    JSONObject res = client.search(imgBash64, "BASE64", "user_01", options);
    JSONObject user = (JSONObject) res.getJSONObject("result").getJSONArray("user_list").get(0);
    Double score = (Double) user.get("score");
    return score;
}

3.6 pages

In fact, the more difficult thing is that the PC terminal needs to call the PC camera to collect the user's face image.

<style type="text/css">
	*{
      
      margin: 0;padding: 0;}
	html,body{
      
      width: 100%;height: 100%;}/**/
	h1{
      
      color: #fff;text-align: center;line-height: 80px;}
	.media{
      
      width: 450px;height: 300px;line-height: 300px;margin: 40px auto;}
	.btn{
      
      width: 250px;height:50px; line-height:50px; margin: 20px auto; text-align: center;}
	#register{
      
      width: 200px;height:50px;background-color: skyblue;text-align: center;line-height: 50px;color: #fff;}
	#canvas{
      
      display: none;}
	#shuru{
      
      width: 250px;height:50px; line-height:50px;background-color: skyblue; margin: 20px auto; text-align: center;}
</style>
</head>
<body>
	<h1>百度云人脸注册</h1>
	<div id="shuru">用户名:<input type="text" name="username" id="username"/></div>
	
	<div class="media">
		<video id="video" width="450" height="300" src="" autoplay></video>
		<canvas id="canvas" width="450" height="300"></canvas>
	</div>
	<div class="btn"><button id="register" >确定注册</button></div>
	<script type="text/javascript" src="js/jquery-3.3.1.js"></script>

	<script type="text/javascript">
	/**调用摄像头,获取媒体视频流**/
	var video = document.getElementById('video');
	//返回画布二维画图环境
	var userContext = canvas.getContext("2d");
	var getUserMedia = 
		//浏览器兼容,表示在火狐、Google、IE等浏览器都可正常支持
		(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia)
		//getUserMedia.call(要调用的对象,约束条件,调用成功的函数,调用失败的函数)
		getUserMedia.call(navigator,{
      
      video: true,audio: false},function(localMediaStream){
      
      
			//获取摄像头捕捉的视频流
			video.srcObject=localMediaStream;
		},function(e){
      
      
			console.log("获取摄像头失败!!")
		});
	//点击按钮注册事件
	 var btn = document.getElementById("register");
	
	btn.onclick = function () {
      
      
		var username = $("#username").val();
		alert($("#username").val());
			if(username != null){
      
      
				//点击按钮时拿到登陆者面部信息
		           userContext.drawImage(video,0,0,450,300);
		           var userImgSrc = document.getElementById("canvas").toDataURL("img/png");
		           //拿到bash64格式的照片信息
		           var faceBase = userImgSrc.split(",")[1];
		           
		           //ajax异步请求
		           $.ajax({
      
      
		        	   url: "register",
		        	   type: "post",
		        	   data: {
      
      "faceBase": faceBase,
		        		   "userName": username
		        	   },
		        	   success: function(result){
      
      
		        		   if(result === '1'){
      
      
		        			   alert("注册成功!!,点击确认跳转至登录页面");
			        		   window.location.href="toLogin";
		        		   }else if(result === '2'){
      
      
		        			   alert("您已经注册过啦!!");
		        		   }else{
      
      
		        			   alert("系统错误!!");
		        		   }
		        	   }
		           })
			}else{
      
      
				alert("用户名不能为空");
			}
       }
	</script>
</body>

3.7 Test results

3.7.1 Register face

It will be stored in the Baidu AI application background, you can check it out. Screenshots are needed, but I didn't show my face during the whole process.

insert image description here

insert image description here

insert image description here

3.7.2 Face login

insert image description here

insert image description here

Source address: https://gitee.com/frank_zxd/springboot-face-ai

Guess you like

Origin blog.csdn.net/zxd1435513775/article/details/124941800