百度人臉識別Java版
阿新 • • 發佈:2018-11-26
作為一個初級碼農,什麼百度雲,阿里雲,騰訊雲都搞一搞,前幾天看到百度的一個AI平臺,挺有意思的,於是乎做了一個人臉識別的小例子。看起來挺牛逼的,做完之後你只會佩服百度的強大!
先展示下專案吧!
通過呼叫攝像頭,實現獲取人臉影象,然後一秒鐘擷取一張視訊影象傳至後臺處理,處理完後則返回使用者資訊。通過這個樣例可以讓專案中的使用者驗證變得高大上。
那我們現在談談他是怎麼實現的?
1.你得註冊個百度雲,建立一個應用
2.點選剛剛建立的應用,檢視一下百度給你的介面。
檢視這兩個介面的URL是否包含該v3的字樣,這就是他幫助文件的意思。
3.我們根據百度給的幫文件看看他具體是怎麼實現的。
4.你用的是百度資源,首先得讓他知道你是誰,然後他才給你使用。這也是token認證的作用。
package com.lb.service; import org.json.JSONObject; import com.lb.token.Token; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; /** * 獲取token類 */ public class GetToken { public static void SaveToken(String url) { String token = getAuth(); System.out.println("token:"+token); Token.token = token; } /** * 獲取許可權token * @return 返回示例: * { * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567", * "expires_in": 2592000 * } */ public static String getAuth() { // 官網獲取的 API Key 更新為你註冊的 String clientId = Token.token; // 官網獲取的 Secret Key 更新為你註冊的 String clientSecret = Token.clientSecret; return getAuth(clientId, clientSecret); } /** * 獲取API訪問token * 該token有一定的有效期,需要自行管理,當失效時需重新獲取. * @param ak - 百度雲官網獲取的 API Key * @param sk - 百度雲官網獲取的 Securet Key * @return assess_token 示例: * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567" */ public static String getAuth(String ak, String sk) { // 獲取token地址 String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1. grant_type為固定引數 + "grant_type=client_credentials" // 2. 官網獲取的 API Key + "&client_id=" + ak // 3. 官網獲取的 Secret Key + "&client_secret=" + sk; try { URL realUrl = new URL(getAccessTokenUrl); // 開啟和URL之間的連線 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 獲取所有響應頭欄位 Map<String, List<String>> map = connection.getHeaderFields(); // 遍歷所有的響應頭欄位 for (String key : map.keySet()) { System.err.println(key + "--->" + map.get(key)); } // 定義 BufferedReader輸入流來讀取URL的響應 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } /** * 返回結果示例 */ System.err.println("result:" + result); JSONObject jsonObject = new JSONObject(result); String access_token = jsonObject.getString("access_token"); return access_token; } catch (Exception e) { System.err.printf("獲取token失敗!"); e.printStackTrace(System.err); } return null; } }
5.獲取到token後我們即可呼叫百度的介面。
根據幫助文件我們只需請求百度的介面,按照上述格式傳遞一些引數,他則返回對比資料給你
package com.lb.service; import com.baidu.ai.aip.utils.HttpUtil; import com.google.gson.Gson; import com.lb.opj.Msg; import com.lb.token.Token; import com.baidu.ai.aip.utils.Base64Util; import com.baidu.ai.aip.utils.FileUtil; import com.baidu.ai.aip.utils.GsonUtils; import java.util.*; /** * 人臉對比 */ public class FaceMatch { /** * 重要提示程式碼中所需工具類 * FileUtil,Base64Util,HttpUtil,GsonUtils請從 * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 * 下載 */ public static String match(String path,byte[] b) { // 請求url String url = "https://aip.baidubce.com/rest/2.0/face/v3/match"; try { //byte[] bytes1 = FileUtil.readFileByBytes(path+"photo/up.png"); byte[] bytes1 = b; byte[] bytes2 = FileUtil.readFileByBytes(path+"photo/lanbing.jpg"); String image1 = Base64Util.encode(bytes1); String image2 = Base64Util.encode(bytes2); List<Map<String, Object>> images = new ArrayList<>(); Map<String, Object> map1 = new HashMap<>(); map1.put("image", image1); map1.put("image_type", "BASE64"); map1.put("face_type", "LIVE"); map1.put("quality_control", "LOW"); map1.put("liveness_control", "NORMAL"); Map<String, Object> map2 = new HashMap<>(); map2.put("image", image2); map2.put("image_type", "BASE64"); map2.put("face_type", "LIVE"); map2.put("quality_control", "LOW"); map2.put("liveness_control", "NORMAL"); images.add(map1); images.add(map2); String param = GsonUtils.toJson(images); // 注意這裡僅為了簡化編碼每一次請求都去獲取access_token,線上環境access_token有過期時間, 客戶端可自行快取,過期後重新獲取。 String accessToken = Token.token; String result = HttpUtil.post(url, accessToken, "application/json", param); System.out.println(result); return result; } catch (Exception e) { e.printStackTrace(); } return null; } public static void Compare(String path,byte[] b) { Gson g = new Gson(); Msg msg = g.fromJson(FaceMatch.match(path,b), Msg.class); System.out.println("匹配得分:"+msg.showScore()); } }
其中他用到了幾個百度的類,具體如下:
package com.baidu.ai.aip.utils;
/**
* Base64 宸ュ叿綾�
*/
public class Base64Util {
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
public Base64Util() {
}
public static String encode(byte[] from) {
StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
int num = 0;
char currentByte = 0;
int i;
for (i = 0; i < from.length; ++i) {
for (num %= 8; num < 8; num += 6) {
switch (num) {
case 0:
currentByte = (char) (from[i] & lead6byte);
currentByte = (char) (currentByte >>> 2);
case 1:
case 3:
case 5:
default:
break;
case 2:
currentByte = (char) (from[i] & last6byte);
break;
case 4:
currentByte = (char) (from[i] & last4byte);
currentByte = (char) (currentByte << 2);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
}
break;
case 6:
currentByte = (char) (from[i] & last2byte);
currentByte = (char) (currentByte << 4);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
}
}
to.append(encodeTable[currentByte]);
}
}
if (to.length() % 4 != 0) {
for (i = 4 - to.length() % 4; i > 0; --i) {
to.append("=");
}
}
return to.toString();
}
}
package com.baidu.ai.aip.utils;
import java.io.*;
/**
* 鏂囦歡璇誨彇宸ュ叿綾�
*/
public class FileUtil {
/**
* 璇誨彇鏂囦歡鍐呭錛屼綔涓哄瓧絎︿覆榪斿洖
*/
public static String readFileAsString(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
if (file.length() > 1024 * 1024 * 1024) {
throw new IOException("File is too large");
}
StringBuilder sb = new StringBuilder((int) (file.length()));
// 鍒涘緩瀛楄妭杈撳靉嫻�
FileInputStream fis = new FileInputStream(filePath);
// 鍒涘緩涓�涓暱搴︿負10240鐨凚uffer
byte[] bbuf = new byte[10240];
// 鐢ㄤ簬淇濆瓨瀹為檯璇誨彇鐨勫瓧鑺傛暟
int hasRead = 0;
while ( (hasRead = fis.read(bbuf)) > 0 ) {
sb.append(new String(bbuf, 0, hasRead));
}
fis.close();
return sb.toString();
}
/**
* 鏍規嵁鏂囦歡璺緞璇誨彇byte[] 鏁扮粍
*/
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
short bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len1;
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
bos.write(buffer, 0, len1);
}
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
}
/*
* Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
*/
package com.baidu.ai.aip.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Json宸ュ叿綾�.
*/
public class GsonUtils {
private static Gson gson = new GsonBuilder().create();
public static String toJson(Object value) {
return gson.toJson(value);
}
public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
return gson.fromJson(json, classOfT);
}
public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
return (T) gson.fromJson(json, typeOfT);
}
}
package com.baidu.ai.aip.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* http 宸ュ叿綾�
*/
public class HttpUtil {
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtil.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺�
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 璁劇疆閫氱敤鐨勮奼傚睘鎬�
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 寰楀埌璇鋒眰鐨勮緭鍑烘祦瀵矽薄
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 寤虹珛瀹為檯鐨勮繛鎺�
connection.connect();
// 鑾峰彇鎵�鏈夊搷搴斿ご瀛楁
Map<String, List<String>> headers = connection.getHeaderFields();
// 閬嶅巻鎵�鏈夌殑鍝嶅簲澶村瓧孌�
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 瀹氫箟 BufferedReader杈撳靉嫻佹潵璇誨彇URL鐨勫搷搴�
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
我們所做的就是按百度的格式給她兩張圖片,然後他就給你結果。我們所做的只此而已。
6.我們如何實現登入註冊呢。
先在我們的應用裡建個人臉庫。
package com.lb.service;
import com.baidu.ai.aip.utils.HttpUtil;
import com.lb.token.Token;
import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.GsonUtils;
import java.io.IOException;
import java.util.*;
/**
* 人臉註冊
*/
public class FaceAdd {
/**
* 重要提示程式碼中所需工具類
* FileUtil,Base64Util,HttpUtil,GsonUtils請從
* https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
* https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
* https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
* https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
* 下載
*/
public static String add(String image,String user_id,String user_info) {
// 請求url
String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
try {
Map<String, Object> map = new HashMap<>();
map.put("image", image);
map.put("group_id", Token.userGroup);
map.put("user_id", user_id);
map.put("user_info", user_info);
map.put("liveness_control", "NORMAL");
map.put("image_type", "BASE64");
map.put("quality_control", "LOW");
String param = GsonUtils.toJson(map);
// 注意這裡僅為了簡化編碼每一次請求都去獲取access_token,線上環境access_token有過期時間, 客戶端可自行快取,過期後重新獲取。
String accessToken = Token.token;
String result = HttpUtil.post(url, accessToken, "application/json", param);
System.out.println(result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
byte[] bytes1;
try {
bytes1 = FileUtil.readFileByBytes("E:\\java02\\faceTest\\WebContent\\photo\\lanbing.jpg");
String image1 = Base64Util.encode(bytes1);
FaceAdd.add(image1,"18897829387","蘭兵");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
7.人臉搜尋
package com.lb.service;
import com.baidu.ai.aip.utils.HttpUtil;
import com.google.gson.Gson;
import com.lb.opj.MsgSearch;
import com.lb.token.Token;
import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.GsonUtils;
import java.io.IOException;
import java.util.*;
/**
* 人臉搜尋
*/
public class FaceSearch {
/**
* 重要提示程式碼中所需工具類
* FileUtil,Base64Util,HttpUtil,GsonUtils請從
* https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
* https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
* https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
* https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
* 下載
*/
public static String search(String image) {
// 請求url
String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
try {
Map<String, Object> map = new HashMap<>();
map.put("image", image);
map.put("liveness_control", "NORMAL");
map.put("group_id_list", Token.userGroup);
map.put("image_type", "BASE64");
map.put("quality_control", "LOW");
String param = GsonUtils.toJson(map);
// 注意這裡僅為了簡化編碼每一次請求都去獲取access_token,線上環境access_token有過期時間, 客戶端可自行快取,過期後重新獲取。
String accessToken = Token.token;
String result = HttpUtil.post(url, accessToken, "application/json", param);
System.out.println(result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String Search(byte[] bytes1) {
String image1 = Base64Util.encode(bytes1);
Gson g = new Gson();
MsgSearch msg = g.fromJson(FaceSearch.search(image1), MsgSearch.class);
return g.toJson(msg.ShowSearched());
}
}
以上是後臺的程式碼,我們只需傳圖片到後臺呼叫即可。
register.html
<!DOCTYPE html>
<html lang="ZH-CN">
<head>
<meta charset="utf-8">
<title>face 測試</title>
<style>
#video {
border: 1px solid #ddd;
}
.booth {
position: relative;
}
.picLine {
border: 1px solid #ddd;
width: 400px;
height: 300px;
position: absolute;
top: 0px;
left: 0px;
}
.vid {
border: 1px solid #ddd;
width: 400px;
height: 300px;
position: absolute;
top: 0px;
left: 0px;
z-index: 99;
}
.screencapture {
border: 1px solid #ddd;
width: 400px;
height: 300px;
position: absolute;
left: 500px;
}
.info {
position: absolute;
top: 350px;
}
</style>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="booth">
<div class="vid">
<video id="video" width="400" height="300"></video>
</div>
</div>
<div>
<div class="screencapture">
<canvas id='canvas' width='400' height='300'></canvas>
</div>
</div>
<div class="info">
<label>賬號:</label> <input type="text" name="account" id="account">
<label>姓名:</label> <input type="text" name="name" id="name"> <br>
<br> <br>
<button id='tack'>註冊</button>
</div>
<script>
var video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
snap = document.getElementById('tack'),
img = document.getElementById('img'),
vendorUrl = window.URL || window.webkitURL;
//媒體物件
navigator.getMedia = navigator.getUserMedia ||
navagator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true, //使用攝像頭物件
audio: false //不適用音訊
}, function (strem) {
console.log(strem);
video.src = vendorUrl.createObjectURL(strem);
video.play();
}, function (error) {
//error.code
console.log(error);
});
snap.addEventListener('click', function () {
//繪製canvas圖形
canvas.getContext('2d').drawImage(video, 0, 0, 400, 300);
var saveImg = canvas.toDataURL('image/png');
var account = document.getElementById("account").value;
var name = document.getElementById("name").value;
$.ajax({
url: "Uploadpic",
type: 'post',
data: {"saveImg":saveImg.substring(22),"name":name,"account":account},
success: function () {
alert('儲存成功');
}
});
})
</script>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="ZH-CN">
<head>
<meta charset="utf-8">
<title>face 測試</title>
<style>
#video {
border: 1px solid #ddd;
}
.booth {
position: relative;
}
.picLine {
border: 1px solid #ddd;
width: 400px;
height: 300px;
position: absolute;
top: 0px;
left: 0px;
}
.vid {
border: 1px solid #ddd;
width: 400px;
height: 300px;
position: absolute;
top: 0px;
left: 0px;
z-index: 99;
}
.screencapture {
border: 1px solid #ddd;
width: 400px;
height: 300px;
position: absolute;
left: 500px;
}
.info {
position: absolute;
top: 350px;
}
</style>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="booth">
<div class="vid">
<video id="video" width="400" height="300"></video>
</div>
</div>
<div>
<div class="screencapture">
<canvas id='canvas' width='400' height='300'></canvas>
</div>
</div>
<div class="info">
<p id="name">adsfsf</p>
</div>
<script>
var video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
snap = document.getElementById('tack'),
img = document.getElementById('img'),
vendorUrl = window.URL || window.webkitURL;
//媒體物件
navigator.getMedia = navigator.getUserMedia ||
navagator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true, //使用攝像頭物件
audio: false //不適用音訊
}, function (strem) {
console.log(strem);
video.src = vendorUrl.createObjectURL(strem);
video.play();
}, function (error) {
//error.code
console.log(error);
});
//擷取圖片並請求後臺
function login() {
var isok = false;
//繪製canvas圖形
canvas.getContext('2d').drawImage(video, 0, 0, 400, 300);
var saveImg = canvas.toDataURL('image/png');
$.ajax({
url: "Login",
type: 'post',
data: {"saveImg":saveImg.substring(22)},
success: function (data) {
document.getElementById("name").innerHTML = data;
this.isok = true;
console.info(data);
}
});
return isok;
}
//隔一秒請求一次
function search(){
var lo = login();
if(lo){
return 0;
}else{
setTimeout(search,1000);
}
}
window.onload=function (){
search();
}
</script>
</body>
</html>
總結:我們所要做的就是獲取使用者影象資訊,通過百度的介面傳給她就OK了·。
完整程式碼:https://download.csdn.net/download/qq_34042417/10700082