当前位置:   article > 正文

Java整合百度云实现人脸识别_java 实现人脸识别登录百度云ai 是免费的么

java 实现人脸识别登录百度云ai 是免费的么

百度云人脸识别属于免费的 个人认证一秒内QPS别超过两次,企业认证后一秒别超过十次 是不收费的

1、首先,开通一个百度云账号

在产品服务里面找到人脸识别这个产品

2、点开之后选择创建应用

3、创建一个应用、起一个名称 点击创建即可

4、打开创建好的应用列表,注意一会就是用的这里的APPID  还有A、K

 

开始上代码,先说场景,这里的需求是显示类似于支付宝刷脸登陆的那种,作为后台来说,只能是前台把照片传给我们,我们再去对比,一开始那种眨眨眼、摇摇头等,那是前端要做的活,只是检测是否为活体,防止用户手动拍着一张静态照片通过,在进行活体检测的时候,百度会给APP端或者前端多张图片,比如说主图、点头的图、摇头图等,我们拿到这些图后,一般拿主图去对比,毕竟可能是唯一的一张正脸照,取出之前存的本人照片,两张都要转成base64去对比

  1. package com.zpkj.common.utils.baiduCloud;
  2. import org.json.JSONObject;
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * Created by 姚洪强 on 2018/8/29.
  11. */
  12. public class AuthService {
  13. /**
  14. * 获取权限token
  15. * @return 返回示例:
  16. * {
  17. * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
  18. * "expires_in": 2592000
  19. * }
  20. */
  21. public static String getAuth() {
  22. // 官网获取的 API Key 更新为你注册的
  23. String clientId = "必须填写";
  24. // 官网获取的 Secret Key 更新为你注册的
  25. String clientSecret = "必须填写";
  26. return getAuth(clientId, clientSecret);
  27. }
  28. /**
  29. * 获取API访问token
  30. * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
  31. * @param ak - 百度云官网获取的 API Key
  32. * @param sk - 百度云官网获取的 Securet Key
  33. * @return assess_token 示例:
  34. * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
  35. */
  36. public static String getAuth(String ak, String sk) {
  37. // 获取token地址
  38. String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
  39. String getAccessTokenUrl = authHost
  40. // 1. grant_type为固定参数
  41. + "grant_type=client_credentials"
  42. // 2. 官网获取的 API Key
  43. + "&client_id=" + ak
  44. // 3. 官网获取的 Secret Key
  45. + "&client_secret=" + sk;
  46. try {
  47. URL realUrl = new URL(getAccessTokenUrl);
  48. // 打开和URL之间的连接
  49. HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
  50. connection.setRequestMethod("GET");
  51. connection.connect();
  52. // 获取所有响应头字段
  53. Map<String, List<String>> map = connection.getHeaderFields();
  54. // 遍历所有的响应头字段
  55. for (String key : map.keySet()) {
  56. System.err.println(key + "--->" + map.get(key));
  57. }
  58. // 定义 BufferedReader输入流来读取URL的响应
  59. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  60. String result = "";
  61. String line;
  62. while ((line = in.readLine()) != null) {
  63. result += line;
  64. }
  65. /**
  66. * 返回结果示例
  67. */
  68. System.err.println("result:" + result);
  69. JSONObject jsonObject = new JSONObject(result);
  70. String access_token = jsonObject.getString("access_token");
  71. return access_token;
  72. } catch (Exception e) {
  73. System.err.printf("获取token失败!");
  74. e.printStackTrace(System.err);
  75. }
  76. return null;
  77. }
  78. }
  1. package com.zpkj.common.utils.baiduCloud;
  2. import com.zpkj.common.utils.baiduCloud.until.Base64Util;
  3. import com.zpkj.common.utils.baiduCloud.until.FileUtil;
  4. import com.zpkj.common.utils.baiduCloud.until.GsonUtils;
  5. import com.zpkj.common.utils.baiduCloud.until.HttpUtil;
  6. import lombok.extern.slf4j.Slf4j;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. * Created by 姚洪强 on 2018/8/29.
  13. */
  14. @Slf4j
  15. public class FaceMatch {
  16. /**
  17. * 重要提示代码中所需工具类
  18. * FileUtil,Base64Util,HttpUtil,GsonUtils请从
  19. * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
  20. * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
  21. * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
  22. * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
  23. * 下载
  24. */
  25. public static String match(String image1Url,String image2Url) {
  26. // 请求url
  27. String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
  28. try {
  29. byte[] bytes1 = FileUtil.readFileByBytes(image1Url);
  30. byte[] bytes2 = FileUtil.readFileByBytes(image2Url);
  31. String image1 = Base64Util.encode(bytes1);
  32. String image2 = Base64Util.encode(bytes2);
  33. List<Map<String, Object>> images = new ArrayList<>();
  34. Map<String, Object> map1 = new HashMap<>();
  35. map1.put("image", image1);
  36. map1.put("image_type", "BASE64");
  37. map1.put("face_type", "LIVE");
  38. map1.put("quality_control", "LOW");
  39. map1.put("liveness_control", "NONE");
  40. Map<String, Object> map2 = new HashMap<>();
  41. map2.put("image", image2);
  42. map2.put("image_type", "BASE64");
  43. map2.put("face_type", "LIVE");
  44. map2.put("quality_control", "LOW");
  45. map2.put("liveness_control", "NONE");
  46. images.add(map1);
  47. images.add(map2);
  48. String param = GsonUtils.toJson(images);
  49. // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
  50. String auth = AuthService.getAuth();
  51. String accessToken = auth;
  52. String result = HttpUtil.post(url, accessToken, "application/json", param);
  53. return result;
  54. } catch (Exception e) {
  55. return "1";
  56. }
  57. }
  58. public static String newMatchFace(byte[] bytes1,String image2Url) {
  59. // 请求url
  60. String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
  61. try {
  62. byte[] bytes2 = FileUtil.readFileByBytes(image2Url);
  63. String image1 = Base64Util.encode(bytes1);
  64. String image2 = Base64Util.encode(bytes2);
  65. List<Map<String, Object>> images = new ArrayList<>();
  66. Map<String, Object> map1 = new HashMap<>();
  67. map1.put("image", image1);
  68. map1.put("image_type", "BASE64");
  69. map1.put("face_type", "LIVE");
  70. map1.put("quality_control", "LOW");
  71. map1.put("liveness_control", "NORMAL");
  72. Map<String, Object> map2 = new HashMap<>();
  73. map2.put("image", image2);
  74. map2.put("image_type", "BASE64");
  75. map2.put("face_type", "LIVE");
  76. map2.put("quality_control", "LOW");
  77. map2.put("liveness_control", "NORMAL");
  78. images.add(map1);
  79. images.add(map2);
  80. String param = GsonUtils.toJson(images);
  81. // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
  82. String auth = AuthService.getAuth();
  83. String accessToken = auth;
  84. String result = HttpUtil.post(url, accessToken, "application/json", param);
  85. return result;
  86. } catch (Exception e) {
  87. return "1";
  88. }
  89. }
  90. public static String newMatchFaceGd(byte[] bytes1,byte[] bytes2) {
  91. // 请求url
  92. String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
  93. try {
  94. String image1 = Base64Util.encode(bytes1);
  95. String image2 = Base64Util.encode(bytes2);
  96. List<Map<String, Object>> images = new ArrayList<>();
  97. Map<String, Object> map1 = new HashMap<>();
  98. map1.put("image", image1);
  99. map1.put("image_type", "BASE64");
  100. map1.put("face_type", "LIVE");
  101. map1.put("quality_control", "LOW");
  102. map1.put("liveness_control", "NORMAL");
  103. Map<String, Object> map2 = new HashMap<>();
  104. map2.put("image", image2);
  105. map2.put("image_type", "BASE64");
  106. map2.put("face_type", "LIVE");
  107. map2.put("quality_control", "LOW");
  108. map2.put("liveness_control", "NORMAL");
  109. images.add(map1);
  110. images.add(map2);
  111. String param = GsonUtils.toJson(images);
  112. // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
  113. String auth = AuthService.getAuth();
  114. String accessToken = auth;
  115. log.info("scr为---------------------------{}"+accessToken);
  116. String result = HttpUtil.post(url, accessToken, "application/json", param);
  117. return result;
  118. } catch (Exception e) {
  119. return "1";
  120. }
  121. }
  122. // public static void main(String[] args) {
  123. // String match = FaceMatch.match("E:\\zpkj\\file\\enclosure\\2019\\04\\11\\7addcf27-4152-478a-857e-fc745822c5be.jpeg", "E:\\zpkj\\file\\enclosure\\2019\\04\\11\\c0d8c232-118c-41c7-87e5-34bad2aed13b.jpeg");
  124. // System.out.println(match.toString());
  125. //
  126. // }
  127. }

上面这两个是工具类,可以先把我注释掉的main方法 打开测试一下,下面上依赖文件

  1. package com.zpkj.common.utils.baiduCloud.until;
  2. import org.springframework.web.multipart.MultipartFile;
  3. import java.io.*;
  4. /**
  5. * Created by 姚洪强 on 2018/7/22.
  6. */
  7. public class BASE64DecodedMultipartFile implements MultipartFile {
  8. private final byte[] imgContent;
  9. private final String header;
  10. public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
  11. this.imgContent = imgContent;
  12. this.header = header.split(";")[0];
  13. }
  14. public String getName() {
  15. // TODO - implementation depends on your requirements
  16. return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
  17. }
  18. public String getOriginalFilename() {
  19. // TODO - implementation depends on your requirements
  20. return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
  21. }
  22. public String getContentType() {
  23. // TODO - implementation depends on your requirements
  24. return header.split(":")[1];
  25. }
  26. public boolean isEmpty() {
  27. return imgContent == null || imgContent.length == 0;
  28. }
  29. public long getSize() {
  30. return imgContent.length;
  31. }
  32. public byte[] getBytes() throws IOException {
  33. return imgContent;
  34. }
  35. public InputStream getInputStream() throws IOException {
  36. return new ByteArrayInputStream(imgContent);
  37. }
  38. public void transferTo(File dest) throws IOException, IllegalStateException {
  39. new FileOutputStream(dest).write(imgContent);
  40. }
  41. }
  1. package com.zpkj.common.utils.baiduCloud.until;
  2. /**
  3. * Base64 工具类
  4. */
  5. public class Base64Util {
  6. private static final char last2byte = (char) Integer.parseInt("00000011", 2);
  7. private static final char last4byte = (char) Integer.parseInt("00001111", 2);
  8. private static final char last6byte = (char) Integer.parseInt("00111111", 2);
  9. private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
  10. private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
  11. private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
  12. 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', '+', '/'};
  13. public Base64Util() {
  14. }
  15. public static String encode(byte[] from) {
  16. StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
  17. int num = 0;
  18. char currentByte = 0;
  19. int i;
  20. for (i = 0; i < from.length; ++i) {
  21. for (num %= 8; num < 8; num += 6) {
  22. switch (num) {
  23. case 0:
  24. currentByte = (char) (from[i] & lead6byte);
  25. currentByte = (char) (currentByte >>> 2);
  26. case 1:
  27. case 3:
  28. case 5:
  29. default:
  30. break;
  31. case 2:
  32. currentByte = (char) (from[i] & last6byte);
  33. break;
  34. case 4:
  35. currentByte = (char) (from[i] & last4byte);
  36. currentByte = (char) (currentByte << 2);
  37. if (i + 1 < from.length) {
  38. currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
  39. }
  40. break;
  41. case 6:
  42. currentByte = (char) (from[i] & last2byte);
  43. currentByte = (char) (currentByte << 4);
  44. if (i + 1 < from.length) {
  45. currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
  46. }
  47. }
  48. to.append(encodeTable[currentByte]);
  49. }
  50. }
  51. if (to.length() % 4 != 0) {
  52. for (i = 4 - to.length() % 4; i > 0; --i) {
  53. to.append("=");
  54. }
  55. }
  56. return to.toString();
  57. }
  58. }
  1. package com.zpkj.common.utils.baiduCloud.until;
  2. import org.springframework.web.multipart.MultipartFile;
  3. import sun.misc.BASE64Encoder;
  4. /**
  5. * Created by 姚洪强 on 2019/4/11.
  6. */
  7. public class FileToBase64 {
  8. public static String test(MultipartFile file) throws Exception{
  9. BASE64Encoder base64Encoder =new BASE64Encoder();
  10. String originalFilename = file.getOriginalFilename();
  11. String base64EncoderImg ="data:"+file.getContentType()+";base64,"+ base64Encoder.encode(file.getBytes());
  12. return base64EncoderImg;
  13. }
  14. }
  1. package com.zpkj.common.utils.baiduCloud.until;
  2. import java.io.*;
  3. /**
  4. * 文件读取工具类
  5. */
  6. public class FileUtil {
  7. public static final int BUFFER_SIZE = 2 * 1024;
  8. /**
  9. * 读取文件内容,作为字符串返回
  10. */
  11. public static String readFileAsString(String filePath) throws IOException {
  12. File file = new File(filePath);
  13. if (!file.exists()) {
  14. throw new FileNotFoundException(filePath);
  15. }
  16. if (file.length() > 1024 * 1024 * 1024) {
  17. throw new IOException("File is too large");
  18. }
  19. StringBuilder sb = new StringBuilder((int) (file.length()));
  20. // 创建字节输入流
  21. FileInputStream fis = new FileInputStream(filePath);
  22. // 创建一个长度为10240的Buffer
  23. byte[] bbuf = new byte[10240];
  24. // 用于保存实际读取的字节数
  25. int hasRead = 0;
  26. while ( (hasRead = fis.read(bbuf)) > 0 ) {
  27. sb.append(new String(bbuf, 0, hasRead));
  28. }
  29. fis.close();
  30. return sb.toString();
  31. }
  32. /**
  33. * 根据文件路径读取byte[] 数组
  34. */
  35. public static byte[] readFileByBytes(String filePath) throws IOException {
  36. File file = new File(filePath);
  37. if (!file.exists()) {
  38. throw new FileNotFoundException(filePath);
  39. } else {
  40. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
  41. BufferedInputStream in = null;
  42. try {
  43. in = new BufferedInputStream(new FileInputStream(file));
  44. short bufSize = 1024;
  45. byte[] buffer = new byte[bufSize];
  46. int len1;
  47. while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
  48. bos.write(buffer, 0, len1);
  49. }
  50. byte[] var7 = bos.toByteArray();
  51. return var7;
  52. } finally {
  53. try {
  54. if (in != null) {
  55. in.close();
  56. }
  57. } catch (IOException var14) {
  58. var14.printStackTrace();
  59. }
  60. bos.close();
  61. }
  62. }
  63. }
  64. }
  1. /*
  2. * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
  3. */
  4. package com.zpkj.common.utils.baiduCloud.until;
  5. import com.google.gson.Gson;
  6. import com.google.gson.GsonBuilder;
  7. import com.google.gson.JsonParseException;
  8. import java.lang.reflect.Type;
  9. /**
  10. * Json工具类.
  11. */
  12. public class GsonUtils {
  13. private static Gson gson = new GsonBuilder().create();
  14. public static String toJson(Object value) {
  15. return gson.toJson(value);
  16. }
  17. public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
  18. return gson.fromJson(json, classOfT);
  19. }
  20. public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
  21. return (T) gson.fromJson(json, typeOfT);
  22. }
  23. }
  1. package com.zpkj.common.utils.baiduCloud.until;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * http 工具类
  11. */
  12. public class HttpUtil {
  13. public static String post(String requestUrl, String accessToken, String params)
  14. throws Exception {
  15. String contentType = "application/x-www-form-urlencoded";
  16. return HttpUtil.post(requestUrl, accessToken, contentType, params);
  17. }
  18. public static String post(String requestUrl, String accessToken, String contentType, String params)
  19. throws Exception {
  20. String encoding = "UTF-8";
  21. if (requestUrl.contains("nlp")) {
  22. encoding = "GBK";
  23. }
  24. return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
  25. }
  26. public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
  27. throws Exception {
  28. String url = requestUrl + "?access_token=" + accessToken;
  29. return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
  30. }
  31. public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
  32. throws Exception {
  33. URL url = new URL(generalUrl);
  34. // 打开和URL之间的连接
  35. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  36. connection.setRequestMethod("POST");
  37. // 设置通用的请求属性
  38. connection.setRequestProperty("Content-Type", contentType);
  39. connection.setRequestProperty("Connection", "Keep-Alive");
  40. connection.setUseCaches(false);
  41. connection.setDoOutput(true);
  42. connection.setDoInput(true);
  43. // 得到请求的输出流对象
  44. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  45. out.write(params.getBytes(encoding));
  46. out.flush();
  47. out.close();
  48. // 建立实际的连接
  49. connection.connect();
  50. // 获取所有响应头字段
  51. Map<String, List<String>> headers = connection.getHeaderFields();
  52. // 遍历所有的响应头字段
  53. for (String key : headers.keySet()) {
  54. System.err.println(key + "--->" + headers.get(key));
  55. }
  56. // 定义 BufferedReader输入流来读取URL的响应
  57. BufferedReader in = null;
  58. in = new BufferedReader(
  59. new InputStreamReader(connection.getInputStream(), encoding));
  60. String result = "";
  61. String getLine;
  62. while ((getLine = in.readLine()) != null) {
  63. result += getLine;
  64. }
  65. in.close();
  66. System.err.println("result:" + result);
  67. return result;
  68. }
  69. }
  1. package com.zpkj.common.utils.baiduCloud.until;
  2. import org.springframework.web.multipart.MultipartFile;
  3. import sun.misc.BASE64Decoder;
  4. import java.io.IOException;
  5. /**
  6. * Created by 姚洪强 on 2018/7/22.
  7. */
  8. public class MultipartFileUtil {
  9. public static MultipartFile base64ToMultipart(String base64) {
  10. try {
  11. String[] baseStrs = base64.split(",");
  12. BASE64Decoder decoder = new BASE64Decoder();
  13. byte[] b = new byte[0];
  14. b = decoder.decodeBuffer(baseStrs[1]);
  15. for(int i = 0; i < b.length; ++i) {
  16. if (b[i] < 0) {
  17. b[i] += 256;
  18. }
  19. }
  20. return new BASE64DecodedMultipartFile(b, baseStrs[0]);
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. return null;
  24. }
  25. }
  26. }

以上就是全部代码,调用工具类返回的result可以读取出来,里面有人脸识别的分值,可以通过自定义分数来判定用户人脸识别是否通过。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/150475
推荐阅读
相关标签
  

闽ICP备14008679号