第一步:鉴权服务技术方案

Java代码实现如下

import java.util.Date;  import com.baidu.aip.util.Base64Util;
/** * 获取Authorization * @author 小帅丶 * @类名称  Sign * @remark  * @date  2017-8-18 */  public class Sign {  /** * Authorization方法 * @param userQQ 开发者创建应用时的QQ号 * @param AppID 开发者创建应用后的AppID * @param SecretID 开发者创建应用后的SecretID * @param SecretKey 开发者创建应用后的SecretKey * @return sign * @throws Exception */  public static String getSign(String userQQ,String AppID,String SecretID,String SecretKey) throws Exception{  long tnowTimes = new Date().getTime()/1000;  long enowTimes = tnowTimes+2592000;  String rRandomNum = HMACSHA1.genRandomNum(10);  String param = "u=" + userQQ + "&a=" + AppID + "&k=" + SecretID + "&e="  + enowTimes + "&t=" + tnowTimes + "&r=" + rRandomNum + "&f=";  byte [] hmacSign = HMACSHA1.getSignature(param, SecretKey);  byte[] all = new byte[hmacSign.length+param.getBytes().length];  System.arraycopy(hmacSign, 0, all, 0, hmacSign.length);  System.arraycopy(param.getBytes(), 0, all, hmacSign.length, param.getBytes().length);  String sign = Base64Util.encode(all);  return sign;  }
}

需要的HMACSHA1代码及随机数代码

    import java.util.Random;  import javax.crypto.Mac;  import javax.crypto.spec.SecretKeySpec;  /** * HMACSHA1算法 *  * @author 小帅丶 * @类名称 HMACSHA1 * @remark * @date 2017-8-18 */  public class HMACSHA1 {  /** * 算法标识 */  private static final String HMAC_SHA1 = "HmacSHA1";  /** * 加密 * @param data 要加密的数据 * @param key 密钥  * @return * @throws Exception */  public static byte[] getSignature(String data, String key) throws Exception {  Mac mac = Mac.getInstance(HMAC_SHA1);  SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),  mac.getAlgorithm());  mac.init(signingKey);  return mac.doFinal(data.getBytes());  }  /** * 生成随机数字 * @param length * @return */  public static String genRandomNum(int length){    int  maxNum = 62;    int i;    int count = 0;    char[] str = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};        StringBuffer pwd = new StringBuffer("");    Random r = new Random();    while(count < length){    i = Math.abs(r.nextInt(maxNum));       if (i >= 0 && i < str.length) {    pwd.append(str[i]);    count ++;    }    }    return pwd.toString();    }   }

第二步:准备相关代码

保存SIGN 或者每次都生成一个也可以 方便测试就直接每次生成一个了

开始识别图片之前需要工具类Base64Util  FileUtil

FileUtil代码

    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();  }  }  }  }

Base64Util  代码

    /** * 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();  }  }

创建应用得到的值放在一个常量类里面

    /** * 常量 * @author 小帅丶 * @类名称  YouTuAppContants * @remark  * @date  2017-8-18 */  public class YouTuAppContants {  public static String AppID = "你自己的AppID ";  public static String SecretID = "你自己的SecretID";  public static String SecretKey = "你自己的SecretKey";  public static String userQQ = "你自己的userQQ";  }

还需要一个HTTPUTIL工具类 发送请求

    import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.IOException;  import java.io.InputStreamReader;  import java.net.HttpURLConnection;  import java.net.URL;  import java.security.KeyManagementException;  import java.security.NoSuchAlgorithmException;  import java.security.cert.CertificateException;  import java.security.cert.X509Certificate;  import javax.net.ssl.HostnameVerifier;  import javax.net.ssl.SSLContext;  import javax.net.ssl.SSLSession;  import javax.net.ssl.TrustManager;  import javax.net.ssl.X509TrustManager;  /** * http 工具类 */  public class HttpUtilYoutu {  private static class TrustAnyTrustManager implements X509TrustManager {  public void checkClientTrusted(X509Certificate[] chain, String authType)  throws CertificateException {  }  public void checkServerTrusted(X509Certificate[] chain, String authType)  throws CertificateException {  }  public X509Certificate[] getAcceptedIssuers() {  return new X509Certificate[] {};  }  }  private static class TrustAnyHostnameVerifier implements HostnameVerifier {  public boolean verify(String hostname, SSLSession session) {  return true;  }  }  /** * post方式请求服务器(https协议) *  * @param url *            请求地址 * @param content *            参数 * @param charset *            编码 * @return * @throws NoSuchAlgorithmException * @throws KeyManagementException * @throws IOException */  public static String post(String url, String content,String charset,String sign)  throws NoSuchAlgorithmException, KeyManagementException,  IOException {  SSLContext sc = SSLContext.getInstance("SSL");  sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },  new java.security.SecureRandom());  URL console = new URL(url);  Integer length = content.length();  HttpURLConnection conn = (HttpURLConnection) console.openConnection();  //文档要求填写的Header参数                  conn.setRequestProperty("Host", "api.youtu.qq.com");  conn.setRequestProperty("Content-Length",length.toString());  conn.setRequestProperty("Content-Type", "text/json");  conn.setRequestProperty("Authorization", sign);  //文档要求填写的Header参数  conn.setDoOutput(true);  conn.connect();  DataOutputStream out = new DataOutputStream(conn.getOutputStream());  out.write(content.getBytes(charset));  // 刷新、关闭  out.flush();  out.close();  BufferedReader in = null;  in = new BufferedReader(  new InputStreamReader(conn.getInputStream(), charset));  String result = "";  String getLine;  while ((getLine = in.readLine()) != null) {  result += getLine;  }  in.close();  System.err.println("result:" + result);  return result;  }  }

第三步:测试一下人脸检测接口

请求示例代码:

import com.xiaoshuai.test.Base64Util;
import com.xiaoshuai.test.FileUtil;  public class DetectFace {  //人脸检测接口  public static String DETECTFACE_URL="http://api.youtu.qq.com/youtu/api/detectface";  public static void main(String[] args) throws Exception {  String p_w_picpathPath = "G:/test2.jpg";  System.out.println(getDetectFace(p_w_picpathPath));  }  /** * 检测图中人脸信息 * @param p_w_picpathPath 图片路径 * @return * @throws Exception */  public static String getDetectFace(String p_w_picpathPath) throws Exception{  //得到Authorization  String sign = Sign.getSign(YouTuAppContants.userQQ,  YouTuAppContants.AppID, YouTuAppContants.SecretID,  YouTuAppContants.SecretKey);  byte[] imgData = FileUtil.readFileByBytes(p_w_picpathPath);  String p_w_picpath =  Base64Util.encode(imgData);;  String param = "{\"app_id\":\""+YouTuAppContants.AppID+"\",\"p_w_picpath\":\""+p_w_picpath+"\"}";  String result = HttpUtilYoutu.post(DETECTFACE_URL, param, "UTF-8",sign);  System.out.println(result);  return result;  }
}

看看返回的内容:

{"session_id":"","p_w_picpath_height":280,"p_w_picpath_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"}

忽略掉检测五官位置的数据:

    "face_id": "2188093443753939350",  "x": 128,  "y": 127,  "height": 106,  "width": 106,  "pitch": 6,  "roll": 3,  "yaw": -2,  "age": 23,//年龄 [0~100]  "gender": 94,//性别 [0/(female)~100(male)]  "glass": true,//是否有眼镜 [true,false]  "expression": 34,//微笑[0(normal)~50(smile)~100(laugh)]  "beauty": 80,//魅力 [0~100]

转载于:https://blog.51cto.com/water12345/1967954

调用腾讯优图开放平台进行人脸识别-Java调用API实现相关推荐

  1. Python调用腾讯优图进行人脸检测分析,并可视化

    opexcel.py import xlrd import xlwt from xlutils.copy import copy class Operatingexcel():def get_exce ...

  2. 基于百度AI开放平台的人脸识别

    文章目录 前言 人脸识别流程图 一.注册账号 二.创建应用 三.下载SDK文件 四.创建工具类 五.创建用于人脸识别的网页 1.引入css文件 2.创建注册按钮 3.创建模态框,用于捕捉人脸 4.引入 ...

  3. 调用腾讯优图OCR手写体文字识别接口

    一.百度搜索:腾讯优图·AI开放平台: 二.点击技术体验中心,可以体验一下效果: 三.点击开发者中心,左侧找到"API文档"里面的"通用手写体文字识别".这里面 ...

  4. Python调用腾讯优图OCR通用API实现文字识别

    API地址:https://ai.qq.com/doc/ocrgeneralocr.shtml 腾讯优图的API比较复杂的就是生成签名,不过不知道腾讯的服务器出什么问题了,调用的时候一直提示504,演 ...

  5. 【论文解读】让特征感受野更灵活,腾讯优图提出非对称卡通人脸检测,推理速度仅50ms...

    该文是腾讯优图&东南大学联合提出一种的非对称卡通人脸检测算法,该方法取得了2020 iCartoon Face Challenge(Under 200MB)竞赛的冠军,推理速度仅为50ms且无 ...

  6. 利用腾讯 优图visionseed硬件 实现人脸疲劳检测项目(包括数据读取,数据保存,数据web端展示)

    一:安装 vision seed SDK 1:如何安装SDK? WIN+R进入cmd工具窗口,通过python pip工具执行命令pip install –upgrade vision安装. 如下: ...

  7. java 百度账号注册界面_基于百度AI开放平台的人脸识别的注册登录(1)

    百度ai开放平台首页 2.选择产品服务,人脸与人体识别,人脸识别选项.打开后如图所示 人脸识别 3.点击立即使用 3.jpg 4.点击创捷应用 创建应用 这一页大家按自己需求填写即可 5.创建完成后点 ...

  8. 百度AI开放平台集成人脸识别,离线采集有动作活体版本sdk

    前言 Android项目Android studio环境: 1.工程build.gradle版本号:3.2.1 2.app目录下的build.gradle配置:compileSdkVersion 28 ...

  9. 基于百度AI开放平台的人脸识别及语音合成

    基于百度AI的人脸识别及语音合成课题 课题需求 (1)人脸识别 在Web界面上传人的照片,后台使用Java技术接收图片,然后对图片进行解码,调用云平台接口识别人脸特征,接收平台返回的人员年龄.性别.颜 ...

最新文章

  1. android 系统锁屏音乐播放器,Android实现音乐播放器锁屏页
  2. The requested profile “pom.xml“ could not be activated because it does not exist. 解决方法
  3. python读取txt文件写入-python 读取、写入txt文件的示例
  4. 网络:长连接、短连接
  5. linux数据同步技术比较,linux下实现web数据同步的四种方式(性能比较)教程.docx
  6. Java io字符流读入英文_Java IO 系列教程(四)-字符输入流(2)
  7. 利用xsl和xml转html没有内容_HTML文档元素的属性介绍
  8. 如何使用APUE源代码(UNIX高级编程)-转
  9. python做oa系统_浅谈python进行webapp,oa系统开发 (更新中) | 学步园
  10. 数据结构上机实践第四周项目3 - 单链表应用
  11. netty实现gmssl_gmssl国密总结
  12. 《Understanding WiFi Signal Frequency Features for Position-Independent Gesture Sensing》论文总结
  13. linux系统查看dns缓存,如何清空linux的DNS缓存
  14. python怎么做大数据_python可以做大数据
  15. Hi3519AV100开启UART串口
  16. 海湾crt调试_海湾设备调试步骤
  17. 培训机构靠谱吗?|猿代码科技
  18. python 构建_通过构建互动游戏来教孩子Python
  19. 开源超融合私有云神器proxmox VE
  20. 【机器学习】李宏毅——Flow-based Generative Models

热门文章

  1. Backbone事件管理——Backbone.Events模块API结构
  2. js(javascript)中__proto__和prototype解析
  3. 3.0 Android组件之间的信使Intent
  4. 自由职业者和外包接单项目分析
  5. 《TCP/IP Sockets编程(C语言实现) (第2版)》 代码下载(链接以及文件打包)
  6. 动易SiteFactory数据采集模块
  7. NEO技术文章征集大赛
  8. Day 41 Rsync备份
  9. NSURLCache详解和使用
  10. python subprocess.Popen简明总结