1. 程式人生 > >調用騰訊優圖開放平臺進行人臉識別-Java調用API實現

調用騰訊優圖開放平臺進行人臉識別-Java調用API實現

ace tno 開放平臺 term href max pre ant water

ttp://open.youtu.qq.com官網

騰訊產品文檔

技術分享

直接234.

第一步:鑒權服務技術方案

Java代碼實現如下

  1. import java.util.Date;
  2. import com.baidu.aip.util.Base64Util;
  3. /**
  4. * 獲取Authorization
  5. * @author 小帥丶
  6. * @類名稱 Sign
  7. * @remark
  8. * @date 2017-8-18
  9. */
  10. public class Sign {
  11. /**
  12. * Authorization方法
  13. * @param userQQ 開發者創建應用時的QQ號
  14. * @param AppID 開發者創建應用後的AppID
  15. * @param SecretID 開發者創建應用後的SecretID
  16. * @param SecretKey 開發者創建應用後的SecretKey
  17. * @return sign
  18. * @throws Exception
  19. */
  20. public static String getSign(String userQQ,String AppID,String SecretID,String SecretKey) throws Exception{
  21. long tnowTimes = new Date().getTime()/1000;
  22. long enowTimes = tnowTimes+2592000;
  23. String rRandomNum = HMACSHA1.genRandomNum(10);
  24. String param = "u=" + userQQ + "&a=" + AppID + "&k=" + SecretID + "&e="
  25. + enowTimes + "&t=" + tnowTimes + "&r=" + rRandomNum + "&f=";
  26. byte [] hmacSign = HMACSHA1.getSignature(param, SecretKey);
  27. byte[] all = new byte[hmacSign.length+param.getBytes().length];
  28. System.arraycopy(hmacSign, 0, all, 0, hmacSign.length);
  29. System.arraycopy(param.getBytes(), 0, all, hmacSign.length, param.getBytes().length);
  30. String sign = Base64Util.encode(all);
  31. return sign;
  32. }
  33. }

需要的HMACSHA1代碼及隨機數代碼

  1. import java.util.Random;
  2. import javax.crypto.Mac;
  3. import javax.crypto.spec.SecretKeySpec;
  4. /**
  5. * HMACSHA1算法
  6. *
  7. * @author 小帥丶
  8. * @類名稱 HMACSHA1
  9. * @remark
  10. * @date 2017-8-18
  11. */
  12. public class HMACSHA1 {
  13. /**
  14. * 算法標識
  15. */
  16. private static final String HMAC_SHA1 = "HmacSHA1";
  17. /**
  18. * 加密
  19. * @param data 要加密的數據
  20. * @param key 密鑰
  21. * @return
  22. * @throws Exception
  23. */
  24. public static byte[] getSignature(String data, String key) throws Exception {
  25. Mac mac = Mac.getInstance(HMAC_SHA1);
  26. SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
  27. mac.getAlgorithm());
  28. mac.init(signingKey);
  29. return mac.doFinal(data.getBytes());
  30. }
  31. /**
  32. * 生成隨機數字
  33. * @param length
  34. * @return
  35. */
  36. public static String genRandomNum(int length){
  37. int maxNum = 62;
  38. int i;
  39. int count = 0;
  40. char[] str = {‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘};
  41. StringBuffer pwd = new StringBuffer("");
  42. Random r = new Random();
  43. while(count < length){
  44. i = Math.abs(r.nextInt(maxNum));
  45. if (i >= 0 && i < str.length) {
  46. pwd.append(str[i]);
  47. count ++;
  48. }
  49. }
  50. return pwd.toString();
  51. }
  52. }

第二步:準備相關代碼

保存SIGN 或者每次都生成一個也可以 方便測試就直接每次生成一個了

開始識別圖片之前需要工具類Base64Util FileUtil

FileUtil代碼

  1. import java.io.*;
  2. /**
  3. * 文件讀取工具類
  4. */
  5. public class FileUtil {
  6. /**
  7. * 讀取文件內容,作為字符串返回
  8. */
  9. public static String readFileAsString(String filePath) throws IOException {
  10. File file = new File(filePath);
  11. if (!file.exists()) {
  12. throw new FileNotFoundException(filePath);
  13. }
  14. if (file.length() > 1024 * 1024 * 1024) {
  15. throw new IOException("File is too large");
  16. }
  17. StringBuilder sb = new StringBuilder((int) (file.length()));
  18. // 創建字節輸入流
  19. FileInputStream fis = new FileInputStream(filePath);
  20. // 創建一個長度為10240的Buffer
  21. byte[] bbuf = new byte[10240];
  22. // 用於保存實際讀取的字節數
  23. int hasRead = 0;
  24. while ( (hasRead = fis.read(bbuf)) > 0 ) {
  25. sb.append(new String(bbuf, 0, hasRead));
  26. }
  27. fis.close();
  28. return sb.toString();
  29. }
  30. /**
  31. * 根據文件路徑讀取byte[] 數組
  32. */
  33. public static byte[] readFileByBytes(String filePath) throws IOException {
  34. File file = new File(filePath);
  35. if (!file.exists()) {
  36. throw new FileNotFoundException(filePath);
  37. } else {
  38. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
  39. BufferedInputStream in = null;
  40. try {
  41. in = new BufferedInputStream(new FileInputStream(file));
  42. short bufSize = 1024;
  43. byte[] buffer = new byte[bufSize];
  44. int len1;
  45. while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
  46. bos.write(buffer, 0, len1);
  47. }
  48. byte[] var7 = bos.toByteArray();
  49. return var7;
  50. } finally {
  51. try {
  52. if (in != null) {
  53. in.close();
  54. }
  55. } catch (IOException var14) {
  56. var14.printStackTrace();
  57. }
  58. bos.close();
  59. }
  60. }
  61. }
  62. }


Base64Util 代碼

  1. /**
  2. * Base64 工具類
  3. */
  4. public class Base64Util {
  5. private static final char last2byte = (char) Integer.parseInt("00000011", 2);
  6. private static final char last4byte = (char) Integer.parseInt("00001111", 2);
  7. private static final char last6byte = (char) Integer.parseInt("00111111", 2);
  8. private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
  9. private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
  10. private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
  11. 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‘, ‘+‘, ‘/‘};
  12. public Base64Util() {
  13. }
  14. public static String encode(byte[] from) {
  15. StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
  16. int num = 0;
  17. char currentByte = 0;
  18. int i;
  19. for (i = 0; i < from.length; ++i) {
  20. for (num %= 8; num < 8; num += 6) {
  21. switch (num) {
  22. case 0:
  23. currentByte = (char) (from[i] & lead6byte);
  24. currentByte = (char) (currentByte >>> 2);
  25. case 1:
  26. case 3:
  27. case 5:
  28. default:
  29. break;
  30. case 2:
  31. currentByte = (char) (from[i] & last6byte);
  32. break;
  33. case 4:
  34. currentByte = (char) (from[i] & last4byte);
  35. currentByte = (char) (currentByte << 2);
  36. if (i + 1 < from.length) {
  37. currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
  38. }
  39. break;
  40. case 6:
  41. currentByte = (char) (from[i] & last2byte);
  42. currentByte = (char) (currentByte << 4);
  43. if (i + 1 < from.length) {
  44. currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
  45. }
  46. }
  47. to.append(encodeTable[currentByte]);
  48. }
  49. }
  50. if (to.length() % 4 != 0) {
  51. for (i = 4 - to.length() % 4; i > 0; --i) {
  52. to.append("=");
  53. }
  54. }
  55. return to.toString();
  56. }
  57. }


創建應用得到的值放在一個常量類裏面

技術分享

  1. /**
  2. * 常量
  3. * @author 小帥丶
  4. * @類名稱 YouTuAppContants
  5. * @remark
  6. * @date 2017-8-18
  7. */
  8. public class YouTuAppContants {
  9. public static String AppID = "你自己的AppID ";
  10. public static String SecretID = "你自己的SecretID";
  11. public static String SecretKey = "你自己的SecretKey";
  12. public static String userQQ = "你自己的userQQ";
  13. }

還需要一個HTTPUTIL工具類

  1. import java.io.BufferedReader;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.security.KeyManagementException;
  8. import java.security.NoSuchAlgorithmException;
  9. import java.security.cert.CertificateException;
  10. import java.security.cert.X509Certificate;
  11. import javax.net.ssl.HostnameVerifier;
  12. import javax.net.ssl.SSLContext;
  13. import javax.net.ssl.SSLSession;
  14. import javax.net.ssl.TrustManager;
  15. import javax.net.ssl.X509TrustManager;
  16. /**
  17. * http 工具類
  18. */
  19. public class HttpUtilYoutu {
  20. private static class TrustAnyTrustManager implements X509TrustManager {
  21. public void checkClientTrusted(X509Certificate[] chain, String authType)
  22. throws CertificateException {
  23. }
  24. public void checkServerTrusted(X509Certificate[] chain, String authType)
  25. throws CertificateException {
  26. }
  27. public X509Certificate[] getAcceptedIssuers() {
  28. return new X509Certificate[] {};
  29. }
  30. }
  31. private static class TrustAnyHostnameVerifier implements HostnameVerifier {
  32. public boolean verify(String hostname, SSLSession session) {
  33. return true;
  34. }
  35. }
  36. /**
  37. * post方式請求服務器(https協議)
  38. *
  39. * @param url
  40. * 請求地址
  41. * @param content
  42. * 參數
  43. * @param charset
  44. * 編碼
  45. * @return
  46. * @throws NoSuchAlgorithmException
  47. * @throws KeyManagementException
  48. * @throws IOException
  49. */
  50. public static String post(String url, String content,String charset,String sign)
  51. throws NoSuchAlgorithmException, KeyManagementException,
  52. IOException {
  53. SSLContext sc = SSLContext.getInstance("SSL");
  54. sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
  55. new java.security.SecureRandom());
  56. URL console = new URL(url);
  57. Integer length = content.length();
  58. HttpURLConnection conn = (HttpURLConnection) console.openConnection();
  59. //文檔要求填寫的Header參數
  60. conn.setRequestProperty("Host", "api.youtu.qq.com");
  61. conn.setRequestProperty("Content-Length",length.toString());
  62. conn.setRequestProperty("Content-Type", "text/json");
  63. conn.setRequestProperty("Authorization", sign);
  64. //文檔要求填寫的Header參數
  65. conn.setDoOutput(true);
  66. conn.connect();
  67. DataOutputStream out = new DataOutputStream(conn.getOutputStream());
  68. out.write(content.getBytes(charset));
  69. // 刷新、關閉
  70. out.flush();
  71. out.close();
  72. BufferedReader in = null;
  73. in = new BufferedReader(
  74. new InputStreamReader(conn.getInputStream(), charset));
  75. String result = "";
  76. String getLine;
  77. while ((getLine = in.readLine()) != null) {
  78. result += getLine;
  79. }
  80. in.close();
  81. System.err.println("result:" + result);
  82. return result;
  83. }
  84. }


第三步:測試一下人臉檢測接口

請求示例類:

  1. import com.xiaoshuai.test.Base64Util;
  2. import com.xiaoshuai.test.FileUtil;
  3. public class DetectFace {
  4. //人臉檢測接口
  5. public static String DETECTFACE_URL="http://api.youtu.qq.com/youtu/api/detectface";
  6. public static void main(String[] args) throws Exception {
  7. String imagePath = "G:/test2.jpg";
  8. System.out.println(getDetectFace(imagePath));
  9. }
  10. /**
  11. * 檢測圖中人臉信息
  12. * @param imagePath 圖片路徑
  13. * @return
  14. * @throws Exception
  15. */
  16. public static String getDetectFace(String imagePath) throws Exception{
  17. //得到Authorization
  18. String sign = Sign.getSign(YouTuAppContants.userQQ,
  19. YouTuAppContants.AppID, YouTuAppContants.SecretID,
  20. YouTuAppContants.SecretKey);
  21. byte[] imgData = FileUtil.readFileByBytes(imagePath);
  22. String image = Base64Util.encode(imgData);;
  23. String param = "{\"app_id\":\""+YouTuAppContants.AppID+"\",\"image\":\""+image+"\"}";
  24. String result = HttpUtilYoutu.post(DETECTFACE_URL, param, "UTF-8",sign);
  25. System.out.println(result);
  26. return result;
  27. }
  28. }


看看返回的內容:

  1. {"session_id":"","image_height":280,"image_width":359,"face":[{"face_id":"2188093443753939350","x":128,"y":127,"height":106.0,"width":106.0,"pitch":6,"roll":3,"yaw":-2,"age":23,"gender":94,"glass":true,"expression":34,"beauty":80,"face_shape":{"face_profile":[{"x":139,"y":160},{"x":139,"y":170},{"x":140,"y":180},{"x":143,"y":189},{"x":146,"y":199},{"x":150,"y":208},{"x":156,"y":217},{"x":162,"y":225},{"x":170,"y":232},{"x":179,"y":236},{"x":189,"y":238},{"x":199,"y":235},{"x":207,"y":230},{"x":214,"y":222},{"x":221,"y":214},{"x":225,"y":205},{"x":229,"y":195},{"x":231,"y":185},{"x":232,"y":174},{"x":233,"y":164},{"x":232,"y":155}],"left_eye":[{"x":152,"y":159},{"x":156,"y":161},{"x":161,"y":163},{"x":166,"y":162},{"x":171,"y":160},{"x":167,"y":157},{"x":162,"y":156},{"x":157,"y":157}],"right_eye":[{"x":216,"y":156},{"x":212,"y":159},{"x":208,"y":160},{"x":203,"y":160},{"x":198,"y":158},{"x":202,"y":155},{"x":206,"y":154},{"x":211,"y":154}],"left_eyebrow":[{"x":143,"y":148},{"x":151,"y":148},{"x":159,"y":148},{"x":166,"y":148},{"x":174,"y":147},{"x":167,"y":142},{"x":158,"y":141},{"x":150,"y":142}],"right_eyebrow":[{"x":224,"y":145},{"x":216,"y":145},{"x":208,"y":145},{"x":200,"y":146},{"x":192,"y":146},{"x":199,"y":141},{"x":208,"y":139},{"x":217,"y":139}],"mouth":[{"x":170,"y":209},{"x":175,"y":214},{"x":180,"y":218},{"x":187,"y":219},{"x":194,"y":217},{"x":200,"y":213},{"x":204,"y":207},{"x":199,"y":203},{"x":192,"y":201},{"x":186,"y":203},{"x":180,"y":202},{"x":174,"y":205},{"x":175,"y":210},{"x":181,"y":211},{"x":187,"y":211},{"x":193,"y":210},{"x":198,"y":209},{"x":198,"y":207},{"x":193,"y":208},{"x":187,"y":209},{"x":180,"y":207},{"x":175,"y":207}],"nose":[{"x":184,"y":184},{"x":183,"y":160},{"x":180,"y":166},{"x":177,"y":173},{"x":174,"y":180},{"x":170,"y":188},{"x":178,"y":191},{"x":185,"y":192},{"x":192,"y":190},{"x":199,"y":186},{"x":194,"y":179},{"x":191,"y":172},{"x":187,"y":166}]}}],"errorcode":0,"errormsg":"OK"}
    1. "face_id": "2188093443753939350",
    2. "x": 128,
    3. "y": 127,
    4. "height": 106,
    5. "width": 106,
    6. "pitch": 6,
    7. "roll": 3,
    8. "yaw": -2,
    9. "age": 23,//年齡 [0~100]
    10. "gender": 94,//性別 [0/(female)~100(male)]
    11. "glass": true,//是否有眼鏡 [true,false]
    12. "expression": 34,//微笑[0(normal)~50(smile)~100(laugh)]
    13. "beauty": 80,//魅力 [0~100]

調用騰訊優圖開放平臺進行人臉識別-Java調用API實現