首页 > 其他分享 >旷视人脸识别代码

旷视人脸识别代码

时间:2023-05-27 20:56:17浏览次数:39  
标签:旷视 人脸识别 return String 代码 conne obos new out

servlet

package com.sxr;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

public class HTTPUtil {
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if (fileMap != null && fileMap.size() > 0) {
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try {
            if (code == 200) {
                ins = conne.getInputStream();
            } else {
                ins = conne.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }

    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }
}

FaceUtil

package com.sxr;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

public class FaceUtil {


    private static HashMap<String, String> map = new HashMap<>();

    static {
        //读取配置文件当中的内容
        Properties pro = new Properties();
        InputStream in = FaceUtil.class.getResourceAsStream("/api.properties");
        try {
            pro.load(in);
            map.put("api_key", pro.getProperty("API_KEY"));
            map.put("api_secret", pro.getProperty("API_SECRET"));
            map.put("display_name", pro.getProperty("DISPLAY_NAME"));
            map.put("outer_id", pro.getProperty("OUTER_ID"));

        } catch (IOException e) {
            System.out.println("配置文件读取错误");
            throw new RuntimeException(e);

        }
    }

    /**
     * 查询指定的人脸是否在人脸集合faceset中存在
     *
     * @param
     * @return
     * @throws Exception
     */


    public static boolean getDetail() throws Exception {
        String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail";
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) {
            return false;


        }
        return true;
    }


    public static boolean createFaceset() throws Exception {
        String url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create";
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) {
            return false;
        }
        return true;
    }


    public static boolean addFace(String faceToken) throws Exception {
        boolean res = getDetail();//先查询是否有知道的人脸集合
        if (!res) {//如果没有就创建
            res = createFaceset();
            if (res) {
                return false;
            }

        }
        String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";
        map.put("face_tokens", faceToken);
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) {
            return false;
        }
        return true;
    }


    /**
     * 查询指定的人脸是否在人脸集合faceset中存在
     *
     * @param faceToken
     * @return
     * @throws Exception
     */
    public static boolean search(String faceToken) throws Exception {
        String url = "https://api-cn.faceplusplus.com/facepp/v3/search";
        map.put("face_token", faceToken);
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) {
            return false;
        }
        //转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONObject thresholdsObject = (JSONObject) jsonObject.get("thresholds");
        double le5 = thresholdsObject.getDoubleValue("le-5");
        //十万分之一的误信率阈值
        JSONArray resArr = (JSONArray) jsonObject.get("results");
        if (resArr != null && resArr.size() >= 1) {
            JSONObject res = (JSONObject) resArr.get(0);
            //取出数组中第一个对象
            double confidence = res.getDoubleValue("confidence");
            if (confidence > le5) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据传入的图片进行人脸检测
     *
     * @param file 传入人脸图片
     * @return 返回人脸照片,如果为空,说明图片有问题
     */

    public static String detect(File file) throws Exception {
        byte[] buff = HTTPUtil.getBytesFromFile(file);
        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";

        HashMap<String, byte[]> byteMap = new HashMap<>();

//        map.put("return_landmark", "1");
//        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_file", buff);
        byte[] bacd = HTTPUtil.post(url, map, byteMap);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) {
            System.out.println("请求发生错误");
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        int num = jsonObject.getIntValue("face_num");
        if (num == 1) {
            JSONArray array = (JSONArray) jsonObject.get("faces");
            JSONObject face = (JSONObject) array.get(0);
            String faceToken = face.getString("face_token");
            return faceToken;
        }

        return null;
    }

}

HTTPUtil

package com.sxr;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

public class HTTPUtil {
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if (fileMap != null && fileMap.size() > 0) {
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try {
            if (code == 200) {
                ins = conne.getInputStream();
            } else {
                ins = conne.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }

    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }
}

TestMain

package com.sxr;

import java.io.*;

public class TestMain {


public static void main(String[] args) {

// File file = new File("C:\\Users\\双休日\\Desktop\\image_file\\a22.jpg");
// try {
// String faceToken = FaceUtil.detect(file);
// System.out.println(faceToken);
// boolean res = FaceUtil.search(faceToken);
// System.out.println("查找结果:" + res);
// FaceUtil.addFace(faceToken);
// res = FaceUtil.search(faceToken);
// System.out.println("查找结果:" + res);
//// boolean res = FaceUtil.getDetail();
//// System.out.println("查找结果:" + res);
//// if (res == false) {
//// res = FaceUtil.createFaceset();
//// System.out.println("创建的faceset--outer_id:test"+res);
//// }
//// res = FaceUtil.getDetail();
//// System.out.println("查找结果:" + res);
//
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }

File file = new File("C:\\Users\\双休日\\Desktop\\image_file\\a1.jpg");
try {
String str = FaceUtil.detect(file);//人脸检测
System.out.println("face_token:" + str);
//添加一个人脸到集合中
boolean addRes = FaceUtil.addFace(str);
System.out.println("添加结果:" + addRes);
boolean res = FaceUtil.search(str);//人脸搜索
System.out.println("搜索结果:" + res);
//获取人脸的集合
// res = FaceUtil.getDetail();

// if (!res) {//如果没有该集合,就创建一个
// res = FaceUtil.createFaceset();
// System.out.println("如果么有指定的人脸集合,则创建新的");
// }
// System.out.println("outer_id为linaFaceset的人脸集合:" + res);

} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
aip.properties
API_KEY=自己的key
API_SECRET=自己的value
DISPLAY_NAME=FaceSet
OUTER_ID=FaceSet

 

标签:旷视,人脸识别,return,String,代码,conne,obos,new,out
From: https://www.cnblogs.com/uninan/p/17437318.html

相关文章

  • 代码随想录算法训练营第十七天|110. 平衡二叉树、257. 二叉树的所有路径
    【参考链接】110.平衡二叉树【注意】1.一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。2.求高度一定要用后序遍历。【代码】1#Definitionforabinarytreenode.2#classTreeNode(object):3#def__init__(self,va......
  • 音频处理数据增强实验与代码分享
    对音频(audio)信号做数据增强(DataAugmentation)可以有多重方式,这里通过sox库、soundfile库、librosa库进行实验,希望可以帮助到有需要的人。可用于深度学习音频处理实验的数据预处理。音高变换增强(PitchShiftAugmentation)音高变化增强,是围绕频率轴的±5%范围内的随机滚动。环绕式......
  • 信源编码的代码实现 (香农编码、费诺编码、哈夫曼编码、游程编码、算术编码)
    @[TOC](文章目录)香农编码(1)将信源消息符号按其出现的概率大小依次排列p1≥p2≥...≥pn(2)确定满足下列不等式的整数码长Ki为-log2(pi)≤Ki<-log2(pi)+1(3)为了编成唯一可译码,计算第i个消息的累加概率(4)将累加概率Pi转换成二进制数。(5)取Pi二进数......
  • 源代码管理工具:提升团队协作与开发效率的利器
    在软件开发领域,源代码管理是一项至关重要的任务。随着团队规模的扩大和项目复杂性的增加,有效地管理和协调代码的变更变得尤为重要。为了应对这一挑战,源代码管理工具应运而生。本文将介绍源代码管理工具的概念、作用以及一些流行的工具,以帮助读者理解并选择适合自己团队的工具。......
  • 低代码的“钱景”——专业的事交给专业的人来做
    你需要知道的低代码低代码通常是指一种可视化的开发方法,用较少的代码、较快的速度来交付应用程序,相似的概念还有“无代码”,也是一种开发方法,通常是面向非技术性员工,让业务人员也可以成为“技术人员”,不需要写任何一行代码来构建应用程序,用低代码甚至无代码创建应用、数据和分析工......
  • 源代码管理工具——GitHub
    GitHub——敏捷开发,CI/CD的倡导者和受益者1.简介GitHub是一个面向开源及私有软件项目的托管平台,因为只支持Git作为唯一的版本库格式进行托管,故名GitHub。Github拥有1亿以上的开发人员,400万以上组织机构和3.3亿以上资料库。2.发展历程GitHub平台于2007年10月1日开始开发,由GitHu......
  • C# 中的字符串——新增功能,通过代码示例进行解释
    我们在代码中使用的大部分内容都是字符串。让我们看一下C#字符串的一些新功能……包括C#11中新增的原始字符串文字和原始字符串插值。原始字符串字面量可以简单灵活地构建复杂的多行字符串,包括JSON。无需逃避。对应视频教程:https://www.java567.com/open/1在本文中,我们将......
  • Python相关性分析代码
    进行相关性分析的代码主要涉及数据处理和统计分析。以下是使用Python进行相关性分析的一般步骤:1.导入必要的库:importpandasaspdimportnumpyasnpimportseabornassnsimportmatplotlib.pyplotasplt2.读取数据:将你的数据加载到PandasDataFrame中。data=pd.read_c......
  • 代码备份
    #include<dlib/image_processing/frontal_face_detector.h>#include<dlib/gui_widgets.h>#include<dlib/image_io.h>#include<iostream>#include<dlib/opencv.h>#include<opencv2/opencv.hpp>#include<dlib/image_proces......
  • 代码生成器
    代码生成器原理是读取表结构,根据表结构的字段名称、数据类型、注释生成实体类,然后根据实体类生成controller和servicefreemarker标签参数${pramName}:根据controller中定义的值,对pramName进行替换<#if>:当结果为true时才会进行展示<p>你好,<#ifuserName=="lyra">......