SpringBoot整合百度云人脸识别功能
1.在百度官网创建应用
首先需要在百度智能云官网中创建应用,获取AppID,API Key,Secret Key
官网地址:https://console.bce.baidu.com/
2.添加百度依赖
添加以下依赖即可。其中版本号可在maven
官网查询
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>${version}</version>
</dependency>
3.在application.yml中添加属性
便于后面去获取值
4.创建AipFace
AipFace
是人脸识别的Java
客户端,为使用人脸识别的开发人员提供了一系列的交互方法。初始化完成后建议单例使用,避免重复获取access_token
(官方原话)
@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);
}
}
5.注册人脸接口
客户端上传的人脸的图片的Base64编码,并将该用户人脸图形进行本地保存,且存入数据库
@Value("${PhotoPath}")
private String filePath;
@Autowired
private AipFace aipFace;
@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);
//判断用户名是否重复
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserName, userName);
User exitUser = userService.getOne(queryWrapper);
if (exitUser != null) {
return "2";
}
userService.save(user);
// 保存上传摄像头捕获的图片
saveLocalImage(faceBase, file);
// 向百度云人脸库插入一张人脸
faceSetAddUser(aipFace,faceBase,user.getUserId());
}
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 userId) {
// 参数为数据库中注册的人脸
HashMap<String, String> options = new HashMap<String, String>();
options.put("user_info", "user's info");
JSONObject res = client.addUser(faceBase, "BASE64", "user_01", userId, options);
return true;
}
6.人脸登录接口
@RequestMapping(value = "login",method = RequestMethod.POST)
public String login(String faceBase) {
String faceData = faceBase;
// 进行人像数据对比
Double num = verifyUser(faceData,aipFace);
if( num > 80) {
return "1";
}else {
return "2";
}
}
public Double verifyUser(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;
}
7.注册登录页面(参考)
其实比较困难的是这个PC端采集用户人脸图像,需要调用PC摄像头。
<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>
8.测试结果
测试成功后,百度平台上能看到用户组下的人脸数增加了