Java 实现人脸识别,手把手教你使用百度AI 实现 人脸识别、人脸对比

r囧r小猫 2021-10-18 15:22 1627阅读 0赞

Java后端 + 百度SDK实现人脸识别

  1. 人工智能越来越贴近我们的生活,相信大家也经常接触到人脸识别,手机付款、app注册验证、门禁等等。
  2. 如果要用Java后台使用这些功能,那么需要怎么做呢?请看完下面这篇文章,就能轻松、简单入门了!

手把手教你实现人脸识别、人脸对比

  1. 注册百度账号 https://ai.baidu.com/
    打开网站,注册百度账号并登录。然后按图1的提示进行操作。
    在图1中,选择 “人脸检测” 跳转到 图2。
    在图2中 点击 “立即使用” 然后跳转到 图3。
    在图3中 点击“创建应用” 然后跳转到 图4.
    在图4中 完成应用申请 然后就有了图5(我们最终需要的就是这个 刚创建应用的参数AppID等)

图1:在这里插入图片描述
图2:
在这里插入图片描述
图3:
在这里插入图片描述
图4:
在这里插入图片描述
图5:
在这里插入图片描述

  1. Java SDK 文档地址:https://ai.baidu.com/docs#/Face-Java-SDK/top
    这里有详细的API文档。
    在这里插入图片描述
  2. pom.xml 配置:


    com.baidu.aip
    java-sdk
    4.10.0
  3. 人脸识别java类
    下面的 APPID/AK/SK 改成你的,找2张人像图片在线生成Base64然后复制在下面就可以测试了。

    import com.baidu.aip.face.AipFace;
    import com.baidu.aip.face.MatchRequest;
    import org.apache.commons.codec.binary.Base64;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;

    public class FaceTest {

    1. //设置APPID/AK/SK
    2. private static String APP_ID = "改成你的图5中的参数";
    3. private static String API_KEY = "改成你的图5中的参数";
    4. private static String SECRET_KEY = "改成你的图5中的参数";
    5. public static void main(String[] args) {
    6. // 初始化一个AipFace
    7. AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    8. // 可选:设置网络连接参数
    9. client.setConnectionTimeoutInMillis(2000);
    10. client.setSocketTimeoutInMillis(60000);
    11. // 可选:设置代理服务器地址, http和socket二选一,或者均不设置

    // client.setHttpProxy(“proxy_host”, proxy_port); // 设置http代理
    // client.setSocketProxy(“proxy_host”, proxy_port); // 设置socket代理

    1. /** START 获取读取 图片Base64编码 **/
    2. // 方法一:
    3. String image1 = "找一张有人脸的图片,在线图片生成Base64编码 然后复制到这里";
    4. String image2 = "找一张有人脸的图片,在线图片生成Base64编码 然后复制到这里";
    5. // 方法二:
    6. /* // 读本地图片 byte[] bytes = FileUtils.fileToBytes("D:\\Documents\\Pictures\\fc.jpg"); byte[] bytes2 = FileUtils.fileToBytes("D:\\Documents\\Pictures\\fj.jpg"); // 将字节转base64 String image1 = Base64.encodeBase64String(bytes); String image2 = Base64.encodeBase64String(bytes2); */
    7. /** END 获取读取 图片Base64编码 **/
    8. // 人脸对比
    9. // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
    10. MatchRequest req1 = new MatchRequest(image1, "BASE64");
    11. MatchRequest req2 = new MatchRequest(image2, "BASE64");
    12. ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
    13. requests.add(req1);
    14. requests.add(req2);
    15. JSONObject res = client.match(requests);
    16. System.out.println(res.toString(2));
    17. // 人脸检测
    18. // 传入可选参数调用接口
    19. HashMap<String, String> options = new HashMap<String, String>();
    20. options.put("face_field", "age");
    21. options.put("max_face_num", "2");
    22. options.put("face_type", "LIVE");
    23. options.put("liveness_control", "LOW");
    24. JSONObject res2 = client.detect(image1, "BASE64", options);
    25. System.out.println(res2.toString(2));
    26. }

    }

上面方法二中的相关类:

Base64.encodeBase64String(bytes) 来自 import org.apache.commons.codec.binary.Base64;
FileUtils.fileToBytes(“D:\Documents\Pictures\fc.jpg”);
FileUtils类 如下:

  1. package com.weixin.demo.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.*;
  5. public class FileUtils {
  6. protected static Logger logger = LoggerFactory.getLogger(FileUtils.class);
  7. public static byte[] fileToBytes(String filePath) {
  8. byte[] buffer = null;
  9. File file = new File(filePath);
  10. FileInputStream fis = null;
  11. ByteArrayOutputStream bos = null;
  12. try {
  13. fis = new FileInputStream(file);
  14. bos = new ByteArrayOutputStream();
  15. byte[] b = new byte[1024];
  16. int n;
  17. while ((n = fis.read(b)) != -1) {
  18. bos.write(b, 0, n);
  19. }
  20. buffer = bos.toByteArray();
  21. } catch (FileNotFoundException ex) {
  22. ex.printStackTrace();
  23. logger.error("", ex);
  24. } catch (IOException ex) {
  25. ex.printStackTrace();
  26. logger.error("", ex);
  27. } finally {
  28. try {
  29. if (null != bos) {
  30. bos.close();
  31. }
  32. } catch (IOException ex) {
  33. ex.printStackTrace();
  34. logger.error("", ex);
  35. } finally {
  36. try {
  37. if (null != fis) {
  38. fis.close();
  39. }
  40. } catch (IOException ex) {
  41. ex.printStackTrace();
  42. logger.error("", ex);
  43. }
  44. }
  45. }
  46. return buffer;
  47. }
  48. public static void bytesToFile(byte[] buffer, final String filePath) {
  49. File file = new File(filePath);
  50. OutputStream output = null;
  51. BufferedOutputStream bufferedOutput = null;
  52. try {
  53. output = new FileOutputStream(file);
  54. bufferedOutput = new BufferedOutputStream(output);
  55. bufferedOutput.write(buffer);
  56. } catch (FileNotFoundException ex) {
  57. ex.printStackTrace();
  58. logger.error("", ex);
  59. } catch (IOException ex) {
  60. ex.printStackTrace();
  61. logger.error("", ex);
  62. } finally {
  63. if (null != bufferedOutput) {
  64. try {
  65. bufferedOutput.close();
  66. } catch (IOException ex) {
  67. ex.printStackTrace();
  68. logger.error("", ex);
  69. }
  70. }
  71. if (null != output) {
  72. try {
  73. output.close();
  74. } catch (IOException ex) {
  75. ex.printStackTrace();
  76. logger.error("", ex);
  77. }
  78. }
  79. }
  80. }
  81. public static void bytesToFile(byte[] buffer, File file) {
  82. OutputStream output = null;
  83. BufferedOutputStream bufferedOutput = null;
  84. try {
  85. output = new FileOutputStream(file);
  86. bufferedOutput = new BufferedOutputStream(output);
  87. bufferedOutput.write(buffer);
  88. } catch (FileNotFoundException ex) {
  89. ex.printStackTrace();
  90. logger.error("", ex);
  91. } catch (IOException ex) {
  92. ex.printStackTrace();
  93. logger.error("", ex);
  94. } finally {
  95. if (null != bufferedOutput) {
  96. try {
  97. bufferedOutput.close();
  98. } catch (IOException ex) {
  99. ex.printStackTrace();
  100. logger.error("", ex);
  101. }
  102. }
  103. if (null != output) {
  104. try {
  105. output.close();
  106. } catch (IOException ex) {
  107. ex.printStackTrace();
  108. logger.error("", ex);
  109. }
  110. }
  111. }
  112. }
  113. /** * byte数组转换成16进制字符串 * * @param src * @return */
  114. public static String bytesToHexString(byte[] src) {
  115. StringBuilder stringBuilder = new StringBuilder();
  116. if (src == null || src.length <= 0) {
  117. return null;
  118. }
  119. for (int i = 0; i < src.length; i++) {
  120. int v = src[i] & 0xFF;
  121. String hv = Integer.toHexString(v);
  122. if (hv.length() < 2) {
  123. stringBuilder.append(0);
  124. }
  125. stringBuilder.append(hv);
  126. }
  127. return stringBuilder.toString();
  128. }
  129. /** * 根据文件流读取图片文件真实类型 */
  130. public static String getTypeByBytes(byte[] fileBytes) {
  131. byte[] b = new byte[4];
  132. System.arraycopy(fileBytes, 0, b, 0, b.length);
  133. String type = bytesToHexString(b).toUpperCase();
  134. if (type.contains("FFD8FF")) {
  135. return "jpg";
  136. } else if (type.contains("89504E47")) {
  137. return "png";
  138. } else if (type.contains("47494638")) {
  139. return "gif";
  140. } else if (type.contains("49492A00")) {
  141. return "tif";
  142. } else if (type.contains("424D")) {
  143. return "bmp";
  144. }
  145. return type;
  146. }
  147. public static String getTypeByFile(File file) {
  148. String fileName = file.getName();
  149. return fileName.substring(fileName.lastIndexOf(".") + 1);
  150. }
  151. public static String getTypeByFilePath(String filePath) {
  152. return filePath.substring(filePath.lastIndexOf(".") + 1);
  153. }
  154. public static byte[] toByteArray(InputStream input) throws IOException {
  155. ByteArrayOutputStream output = new ByteArrayOutputStream();
  156. byte[] buffer = new byte[4096];
  157. int n = 0;
  158. while (-1 != (n = input.read(buffer))) {
  159. output.write(buffer, 0, n);
  160. }
  161. return output.toByteArray();
  162. }
  163. }

“人脸对比” 测试结果:
主要看 score 参数,越高越匹配。满分100分。

  1. 0 [main] INFO com.baidu.aip.client.BaseClient - get access_token success. current state: STATE_AIP_AUTH_OK
  2. 2 [main] DEBUG com.baidu.aip.client.BaseClient - current state after check priviledge: STATE_TRUE_AIP_USER
  3. {
  4. "result": {
  5. "score": 90.39932251,
  6. "face_list": [
  7. {"face_token": "594b9857e1bc1a6f0bb6fa7183ca962d"},
  8. {"face_token": "f552428debe38d54081dfbce5d6d6e1e"}
  9. ]
  10. },
  11. "log_id": 1345050756015080031,
  12. "error_msg": "SUCCESS",
  13. "cached": 0,
  14. "error_code": 0,
  15. "timestamp": 1565601508
  16. }

“人脸检测” 测试结果:

  1. {
  2. "result": {
  3. "face_num": 1,
  4. "face_list": [{
  5. "liveness": {"livemapscore": 1},
  6. "angle": {
  7. "roll": -3.24,
  8. "pitch": 13.22,
  9. "yaw": 7.82
  10. },
  11. "face_token": "594b9857e1bc1a6f0bb6fa7183ca962d",
  12. "location": {
  13. "top": 570.86,
  14. "left": 197.56,
  15. "rotation": 1,
  16. "width": 339,
  17. "height": 325
  18. },
  19. "face_probability": 1,
  20. "age": 23
  21. }]
  22. },
  23. "log_id": 1368654456015085521,
  24. "error_msg": "SUCCESS",
  25. "cached": 0,
  26. "error_code": 0,
  27. "timestamp": 1565601508
  28. }

人脸检测 相关请求参数、返回参数解释。(详情请访问第2点的SDK地址:即 https://ai.baidu.com/docs#/Face-Java-SDK/top)
在这里插入图片描述
在这里插入图片描述
人脸对比 相关请求参数、返回参数解释。(详情请访问第2点的SDK地址:即 https://ai.baidu.com/docs#/Face-Java-SDK/top)
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,1627人围观)

还没有评论,来说两句吧...

相关阅读