人脸—>face_token

人脸 在人脸识别技术中特指图像中发现的人脸,当对一张图片进行人脸检测时,会将监测到的人脸记录下来,包括人脸在图片的位置,用一个系统标识face_token来表示

人脸集合—>faceSet

人脸集合是用来存储检测到的的人脸存储对象 一个FaceSet内face_token是不重复的

人脸搜索

计算机检测到一个人脸后,通过人脸判断人身份的过程叫着人脸搜索 ,指的是采集用户新的人脸,在多个已知已知身份用户的人脸集合中进行搜索找出新的人脸属于哪一个已知身份用户,人脸搜索需要SearchAPI

Face++使用方式

1.去https://console.faceplusplus.com.cn/documents/6329752API入门查看代码实例将代码实例全部拷贝下来

  1. public static void main(String[] args) throws Exception{
  2. String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
  3. File file = new File(path+"/lk.jpg");//将图片获取过滤
  4. byte[] buff = getBytesFromFile(file);//将文件变成byte数组
  5. String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";//调用的api地址
  6. HashMap<String, String> map = new HashMap<String, String>();//传的参数地址
  7. HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();//传图片地址
  8. map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
  9. map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
  10. map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
  11. byteMap.put("image_file", buff);
  12. try{
  13. byte[] bacd = post(url, map, byteMap);
  14. String str = new String(bacd);
  15. System.out.println(str);
  16. }catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. //======以下代码不需要做任何修改=====
  21. private final static int CONNECT_TIME_OUT = 30000;
  22. private final static int READ_OUT_TIME = 50000;
  23. private static String boundaryString = getBoundary();
  24. protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
  25. HttpURLConnection conne;
  26. URL url1 = new URL(url);
  27. conne = (HttpURLConnection) url1.openConnection();
  28. conne.setDoOutput(true);
  29. conne.setUseCaches(false);
  30. conne.setRequestMethod("POST");
  31. conne.setConnectTimeout(CONNECT_TIME_OUT);
  32. conne.setReadTimeout(READ_OUT_TIME);
  33. conne.setRequestProperty("accept", "*/*");
  34. conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
  35. conne.setRequestProperty("connection", "Keep-Alive");
  36. conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
  37. DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
  38. Iterator iter = map.entrySet().iterator();
  39. while(iter.hasNext()){
  40. Map.Entry<String, String> entry = (Map.Entry) iter.next();
  41. String key = entry.getKey();
  42. String value = entry.getValue();
  43. obos.writeBytes("--" + boundaryString + "\r\n");
  44. obos.writeBytes("Content-Disposition: form-data; name=\"" + key
  45. + "\"\r\n");
  46. obos.writeBytes("\r\n");
  47. obos.writeBytes(value + "\r\n");
  48. }
  49. if(fileMap != null && fileMap.size() > 0){
  50. Iterator fileIter = fileMap.entrySet().iterator();
  51. while(fileIter.hasNext()){
  52. Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
  53. obos.writeBytes("--" + boundaryString + "\r\n");
  54. obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
  55. + "\"; filename=\"" + encode(" ") + "\"\r\n");
  56. obos.writeBytes("\r\n");
  57. obos.write(fileEntry.getValue());
  58. obos.writeBytes("\r\n");
  59. }
  60. }
  61. obos.writeBytes("--" + boundaryString + "--" + "\r\n");
  62. obos.writeBytes("\r\n");
  63. obos.flush();
  64. obos.close();
  65. InputStream ins = null;
  66. int code = conne.getResponseCode();
  67. try{
  68. if(code == 200){
  69. ins = conne.getInputStream();
  70. }else{
  71. ins = conne.getErrorStream();
  72. }
  73. }catch (SSLException e){
  74. e.printStackTrace();
  75. return new byte[0];
  76. }
  77. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  78. byte[] buff = new byte[4096];
  79. int len;
  80. while((len = ins.read(buff)) != -1){
  81. baos.write(buff, 0, len);
  82. }
  83. byte[] bytes = baos.toByteArray();
  84. ins.close();
  85. return bytes;
  86. }
  87. private static String getBoundary() {
  88. StringBuilder sb = new StringBuilder();
  89. Random random = new Random();
  90. for(int i = 0; i < 32; ++i) {
  91. sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
  92. }
  93. return sb.toString();
  94. }
  95. private static String encode(String value) throws Exception{
  96. return URLEncoder.encode(value, "UTF-8");
  97. }
  98. public static byte[] getBytesFromFile(File f) {
  99. if (f == null) {
  100. return null;
  101. }
  102. try {
  103. FileInputStream stream = new FileInputStream(f);
  104. ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
  105. byte[] b = new byte[1000];
  106. int n;
  107. while ((n = stream.read(b)) != -1)
  108. out.write(b, 0, n);
  109. stream.close();
  110. out.close();
  111. return out.toByteArray();
  112. } catch (IOException e) {
  113. }
  114. return null;
  115. }

2.调用不同API只需要更改地址 将不同的参数写入map就可以了 byteMap传图片文件的时候需要 不用设置成null就可以 规范给出的代码实例main一下的方法不要变动 变动API增加参数只需要增加map中的内容就可以

两张图片比较—无byteMap

  //两张照片的比较
    public static double compareImg(String face_token1,String face_token2){
        String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
        map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
        map.put("image_file1", face_token1);
        map.put("image_file2",face_token2);
        try{
            byte[] bacd = post(url, map, null);//调用post方法获取结果
            String str = new String(bacd);//将字节数组转成字符串
            if (str.contains("error_message")) {
                System.out.println("发生了错误");
                return 0;
            }
            JsonObject jsonObject = new Gson().fromJson(str, JsonObject.class);
            JsonElement confidence = jsonObject.get("confidence");
            double asDouble = confidence.getAsDouble();
          return asDouble;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

3.如果使用搜索API必须将图片的face_token加入到FaceSet中去 使用FaceSet必须要创建

创建和将face_token加入到FaceSet中去

 //创建一个FaceSet
public static void createFaceSet() {
    String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/create";
    HashMap<String, String> map = new HashMap<String, String>();
    HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();
    map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
    map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
    map.put("outer_id", "lkFaceSet"); //faceSetID固定不更改了
    try {
        byte[] bacd = post(url, map, null);//调用post方法获取结果
        String str = new String(bacd);//将字节数组转成字符串
        System.out.println(str);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 //将生成的face_token添加到FaceSet中
public static String face_tokenAddFaceSet(String face_token) {
    String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";
    HashMap<String, String> map = new HashMap<String, String>();
    HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();
    map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
    map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
    map.put("outer_id", "lkFaceSet");
    map.put("face_tokens", face_token);
    try {
        byte[] bacd = post(url, map, null);//调用post方法获取结果
        String str = new String(bacd);//将字节数组转成字符串
        System.out.println(str);
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
    return null;
}
//从FaceSet中搜索出相似度最高的照片
public static String search(String search) throws Exception {
    String url = "https://api-cn.faceplusplus.com/facepp/v3/search";
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
    map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
    map.put("outer_id", "lkFaceSet");//faceSet的自定义ID
    map.put("face_token", search);
    try {
        byte[] bacd = post(url, map, null);//调用post方法获取结果
        String str = new String(bacd);//将字节数组转成字符串
        System.out.println(str);
    } catch (Exception e) {
        e.printStackTrace();
        }
    return null;
}

具体实现

前端

调用摄像头

<video src="" id="video" style="border:1px solid red;display: none" width="200px"></video>
<canvas id="canvas"></canvas>
<div id="div1" style="background:rosybrown;width: 200px;height: 200px">开启摄像头</div>
<div id="div" style="background:rosybrown;width: 200px;height: 200px">拍照</div>
<script>
 var video = document.getElementById('video');
 var div = document.getElementById('div');
 var div1 = document.getElementById('div1');
 var img = document.getElementById('img');
 var canvas = document.getElementById('canvas');
//开启摄像头
 div.onclick = () => {
        video.style["display"] = "block"
           //navigator.mediaDevices.getUserMedia()开启摄像头的方法 成功后有个回参 video接收 启动
        navigator.mediaDevices.getUserMedia({video: true}).then(res => {
            video.srcObject = res;
            video.play();
        })
    }
//通过cavas生成图片
 div1.onclick = () => {
   let ctx = canvas.getContext('2d');
               //将视频中的图片化成图片
   ctx.drawImage(document.getElementById("video"), 0, 0, 200, 200)
               //toDataURL方法会把图片转成一个Base64加密数据 参数可以设置图片出来的格式 默认image/jpeg\
              ////data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAS大概的样子是这样的 逗号后面才是真正要的加密数据要进行截取
   var data = canvas.toDataURL("image/png");
   console.log(data.split(',')[1])
   //将真正的加密数据传给后端
   axios.post("search2",{base:JSON.stringify(data.split(',')[1])}).then(res=>{
         })
    }
</script>

后端

 @PostMapping("/search2")
 @ResponseBody
public String adds(@RequestBody String base) throws IOException {
        //将数据转成JsonObject对象
    {"base":"iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAY..."}大概是这个样子的就是到的内容
        JsonObject jsonObject = new Gson().fromJson(base, JsonObject.class);
        //将json中的加密字符串提取出来两边引号去掉 通过hutoolBase64进行界面将得到的byte[]进行输出
        byte[] decode = Base64.decode(jsonObject.get("base").toString().substring(1,jsonObject.get("base").toString().length() - 1));
        //创建一个输出流 将byte[]转成图片保存下来
           OutputStream os = new FileOutputStream("abc.png");
        os.write(decode,0,decode.length);
        os.flush();
        os.close();
        return "rest";
    }