百度人脸识别工具类
package com.sxit.app.util;
/** 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.sxit.app.util;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sxit.app.entity.bo.FaceInfo;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 胡乖乖童鞋
* @date 2022/1/9 20:28
* @describe
*/
@Slf4j
public class FaceUtil {
// 官网获取的 API Key 更新为你注册的
private static final String clientId = "";
// 官网获取的 Secret Key 更新为你注册的
private static final String clientSecret = "";
// accessToken
private static final String accessToken =
"[]";
// 分组信息
private static final String group_id = "emos";
/**
* 获取对应权限
*
* @return
*/
public static String getAuth() {
return getAuth(clientId, clientSecret);
}
/**
* 获取API访问token 该token有一定的有效期,需要自行管理,当失效时需重新获取.
*
* @param ak - 百度云官网获取的 API Key
* @param sk - 百度云官网获取的 Secret Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
private 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.getStr("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
}
/**
* 通过读取文件路径,获取图片中的人脸数据
*
* @param filePath 图片的位置
* @return
*/
public static String getFaceInfoByFilePath(String filePath) throws IOException {
// 1. 根据文件路径读取byte[] 数组,并将数组进行Base64编码
byte[] bytes = FileUtil.readFileByBytes(filePath);
String encode = Base64Util.encode(bytes);
try {
// 2.讲封装好的参数发送到目标地址,并返回人脸数据用于人脸检测
String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
Map<String, Object> map = new HashMap<>();
map.put("image", encode); // 图片的基本信息和方式
map.put("image_type", "BASE64"); // 编码方式
map.put("face_type", "LIVE"); // 人脸的类型 这里选择生活照
String param = GsonUtils.toJson(map);
return HttpUtil.post(url, accessToken, "application/json", param);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 通过读取字节码,获取图片中的人脸数据
*
* @param fileBates 图片的字节码
* @return
*/
public static String getFaceInfoByFileBytes(byte[] fileBates) throws IOException {
// 1. 根据读取byte[] 数组,并将数组进行Base64编码
String encode = Base64Util.encode(fileBates);
try {
// 2.讲封装好的参数发送到目标地址,并返回人脸数据用于人脸检测
String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
Map<String, Object> map = new HashMap<>();
map.put("image", encode); // 图片的基本信息和方式
map.put("image_type", "BASE64"); // 编码方式
map.put("face_type", "LIVE"); // 人脸的类型 这里选择生活照
String param = GsonUtils.toJson(map);
return HttpUtil.post(url, accessToken, "application/json", param);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 根据 图片1和图片2的数据进行对比 判断是否为同一个人
*
* @param bytes
* @param armFaceToken
* @return
*/
public static Boolean faceContrast(byte[] bytes, String armFaceToken, String userId) {
String path = "https://aip.baidubce.com/rest/2.0/face/v3/match";
String encode = Base64Util.encode(bytes);
try {
List<Map<String, Object>> maps = new ArrayList<>();
Map<String, Object> imageOne = new HashMap<>();
imageOne.put("image", encode);
imageOne.put("image_type", "BASE64");
imageOne.put("face_type", "LIVE");
Map<String, Object> imageTwo = new HashMap<>();
imageTwo.put("image", armFaceToken);
imageTwo.put("image_type", "FACE_TOKEN");
imageTwo.put("face_type", "LIVE");
maps.add(imageOne);
maps.add(imageTwo);
String param = GsonUtils.toJson(maps);
String result = HttpUtil.post(path, accessToken, "application/json", param);
String sorce = getSorce(result);
return Integer.parseInt(sorce) > 80;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 通过字节码讲人脸数据注册到人脸库
*
* @param bytes
* @param userId
* @return
*/
public static String getFaceToken(byte[] bytes, String userId) {
String encode = Base64Util.encode(bytes);
// 请求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", encode);
map.put("group_id", group_id);
map.put("user_id", userId);
map.put("user_info", userId + "的数据");
map.put("liveness_control", "NORMAL");
map.put("image_type", "BASE64");
map.put("quality_control", "LOW");
String param = GsonUtils.toJson(map);
String result = HttpUtil.post(url, accessToken, "application/json", param);
FaceInfo faceInfo = JSON.parseObject(result, FaceInfo.class);
String face_token = faceInfo.getResult().getFace_token();
return face_token;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过读取文件位置读取文件后讲人脸数据注册到人脸库
*
* @param filePath
* @param userId
* @return
*/
public static String getFaceToken(String filePath, String userId) throws IOException {
byte[] bytes = FileUtil.readFileByBytes(filePath);
String encode = Base64Util.encode(bytes);
// 请求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", encode);
map.put("group_id", "emos");
map.put("user_id", userId);
map.put("user_info", userId + "的人脸数据");
map.put("liveness_control", "NORMAL");
map.put("image_type", "BASE64");
map.put("quality_control", "LOW");
String param = GsonUtils.toJson(map);
String result = HttpUtil.post(url, accessToken, "application/json", param);
FaceInfo faceInfo = JSON.parseObject(result, FaceInfo.class);
String face_token = faceInfo.getResult().getFace_token();
return face_token;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 删除faceToken
*
* @param token
* @param userId
*/
public static boolean deleteFaceToken(String token, String userId) {
String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete";
try {
Map<String, Object> map = new HashMap<>();
map.put("user_id", userId);
map.put("group_id", group_id);
map.put("face_token", token);
map.put("log_id", 0);
String param = GsonUtils.toJson(map);
String result = HttpUtil.post(url, accessToken, "application/json", param);
log.info(result);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 获取Ren脸识别中的score
*
* @param key
* @return
*/
private static String getSorce(String key) {
JsonParser jp = new JsonParser();
// 将json字符串转化成json对象
JsonObject jo = jp.parse(key).getAsJsonObject();
String score = jo.get("result").getAsJsonObject().get("score").getAsString();
return score;
}
}
package com.sxit.app.util;
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的Buffer
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();
}
}
}
}
package com.sxit.app.util; /*
* Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
*/
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 final 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.sxit.app.util;
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);
// 打开和URL之间的连接
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;
}
}