賬号登入成功,您需要建立應用才可正式調用AI能力。應用是您調用API服務的基本操作單元,您可以基于應用建立成功後擷取的API Key及Secret Key,進行接口調用操作,及相關配置。
第一步:去百度智能雲新增賬號登入:連結:百度智能雲-登入 (baidu.com)
第二步:找到右側頂部藍色三條杠點選-->産品服務-->人工智能-->人臉識别

第三步:按照首頁概括操作
關于建立應用教程:
第四步建立好後保留以下三個字段
AppID | API Key | Secret Key |
---|
廢話不多說直接上代碼
1.建立一個spring boot項目
2.導入maven依賴
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.7</version>
</dependency>
3.建立資料庫,如下圖所示
4.配置yml
baidu:
appId: 剛剛建立号應用儲存的appId
key: 剛剛建立号應用儲存的key
secret: 剛剛建立号應用儲存的secret
如圖所示:
5.
import com.baidu.aip.face.AipFace;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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);
}
}
6.
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Users {
private Integer id;
private String userName;
private String userPhoto;
}
----------------------------------都在代碼塊中了哈------------------------------------------
第七步:
import com.baidu.aip.face.AipFace;
import com.face.config.BaiduConfig;
import com.face.dao.UsersMapper;
import com.face.pojo.Users;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
@RestController
@CrossOrigin
public class FaceController {
/*上傳路徑*/
private String filePath="路徑";
@Autowired
private BaiduConfig baiduConfig;
/*資料庫*/
@Autowired
private UsersMapper usersMapper;
@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 = usersMapper.selectUserByName(user);
if(exitUser != null) {
return "2";
}
usersMapper.addUsers(user);
// 儲存上傳攝像頭捕獲的圖檔
saveLocalImage(faceBase, file);
// 向百度雲人臉庫插入一張人臉
faceSetAddUser(baiduConfig.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;
}
@RequestMapping(value = "login",method = RequestMethod.POST)
public String login(String faceBase) {
String faceData = faceBase;
// 進行人像資料對比
Double num = checkUser(faceData,baiduConfig.aipFace());
if( num > 80) {
return "1";
}else {
return "2";
}
}
public Double checkUser(String imgBash64,AipFace client) {
// 傳入可選參數調用接口
HashMap<String, Object> options = new HashMap<String, Object>();
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;
}
}
----------------------------------------------------------------------------------------
第八步:
import com.face.pojo.Users;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UsersMapper {
@Insert("insert into users values (#{id},#{userName},#{userPhoto})")
Integer addUsers(Users users);
@Select("select*from users where user_name=#{userName}")
Users selectUserByName(Users users);
}
第九步:注冊前端頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
/**解決浏覽器相容性問題**/
*{margin: 0;padding: 0;}
html,body{width: 100%;height: 100%;}/**/
/*body{background: url(ac.jpg) no-repeat center;}*/
h1{color: #fff;text-align: center;line-height: 80px;}
.media{width: 534px;height: 400px;margin: 40px auto 0;
}
#register{width: 200px;height:50px;background-color: #2196f3; margin-left: 640px;
text-align: center;line-height: 50px;color: #fff;border-radius: 10px;}
#canvas{display: none;}
/*#shuru{width: 200px;height:50px;background-color: #2196f3; margin: 20px auto 0;}*/
#shuru{width: 200px;height:30px; margin: 0 auto;}
</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>
<button id="register" >确定注冊</button>
<script type="text/javascript" src="https://libs.baidu.com/jquery/2.1.4/jquery.min.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: "http://127.0.0.1:8080/register",
type: "post",
data: {"faceBase": faceBase,
"userName": username
},
success: function(result){
if(result === '1'){
alert("注冊成功!!,點選确認跳轉至登入頁面");
window.location.href="fac2.html" target="_blank" rel="external nofollow" ;
}else if(result === '2'){
alert("您已經注冊過啦!!");
}else{
alert("系統錯誤!!");
}
}
})
}else{
alert("使用者名不能為空");
}
}
</script>
</body>
</html>
----------------------------------------------------------------------------------------
第十步:登入前端頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
*{margin: 0;padding: 0;}
html,body{width: 100%;height: 100%;}/**/
h1{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;}
#login{width: 200px;height:50px;background-color: skyblue;text-align: center;line-height: 50px;color: #fff;}
#canvas{display: none;}
</style>
</head>
<body>
<h1>登入</h1>
<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="login" >登入按鈕</button></div>
<script type="text/javascript" src="https://libs.baidu.com/jquery/2.1.4/jquery.min.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("login");
btn.onclick = function () {
//點選按鈕時拿到登陸者面部資訊
userContext.drawImage(video,0,0,450,300);
var userImgSrc = document.getElementById("canvas").toDataURL("img/png");
//拿到bash64格式的照片資訊
var faceBase = userImgSrc.split(",")[1];
//ajax異步請求
$.ajax({
url: "http://127.0.0.1:8080/login",
type: "post",
data: {"faceBase": faceBase},
success: function(result){
if(result==='1'){
alert("登入成功!!")
//跳轉至登入頁面
// window.location.href="toSuccess" target="_blank" rel="external nofollow" ;
}else{
alert("人臉識别失敗!!");
//跳轉至登入失敗頁面
// window.location.href="toErro" target="_blank" rel="external nofollow" ;
}
}
})
}
</script>
</body>
</html>