【人脸检测】JavaAPI调用示例
用户已被禁言 发布于2017-10 浏览:3418 回复:10
3
收藏
最后编辑于2022-04

链接:https://yun.baidu.com/s/1ht3H9pq 密码:uxxf 示例项目下载地址

1.官网文档必须看

http://ai.baidu.com/docs

2.在管理中心创建应用及查看相关参数 AppID APIKey SecretKey都需要保存起来

 

3.搬砖测试

项目需要的lib包,基本下载官网的SDK就都会包含。

package com.xs.demo.common;
//相关的必要参数可以保存到常量
public class APIConstants {
	//百度人脸识别应用id
	public static final String APPID = "管理中心获得";
	//百度人脸识别应用apikey
	public static final String API_KEY = "管理中心获得";
	//百度人脸识别应用sercetkey
	public static final String SERCET_KEY = "管理中心获得";
	//百度人脸识别token 有效期一个月
	public static final String TOKEN = "为了测试,将生成的key先存一下";
}

4.获取AccessToken

官网文档说明http://ai.baidu.com/docs#Beginner-Auth

向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

  • grant_type: 必须参数,固定为“client_credentials”;
    client_id: 必须参数,应用的API Key;
    client_secret: 必须参数,应用的Secret Key;
    直接在浏览器GET请求也可以获取:

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=APIKEY&client_secret=SECRETKEY

//获取AccessToken 有效期一个月
public class AITest {
	public static void main(String[] args) throws Exception {;
		String access_token_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials" +
				"&client_id="+APIContants.API_KEY
			   +"&client_secret="+ APIContants.SERCET_KEY;
		HttpResponse response = HttpUtils.doPostBD(access_token_url,new HashMap(),new HashMap());
		System.out.println(EntityUtils.toString(response.getEntity()));
		
	}
}
//返回的JSON数据。只需要access_token即可
{"access_token":"24.39b6fc97e87058ed6edb92ad68782c29.2592000.1492651482.11111-11111","session_key":"9mzdCP1XKXZ5yipkl7ubftudl2reGQybIG25NqWi9vqeSFFjxigLFl+WpfDW0PyUt7EP\/Uyn74r31lj3d4kVr4xkbkSk","scope":"public vis-faceverify_faceverify vis-faceattribute_faceattribute wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian wangrantest_test wangrantest_test1 bnstest_test1 bnstest_test2 ApsMisTest_Test\u6743\u9650 vis-classify_flower","refresh_token":"25.3c8370eaeb8af4f8367a38b6dbefcef9.315360000.1805419482.11111-11111","session_secret":"ff06850552b385cff19de958e435e6a4","expires_in":2592000}

5.HttpUtils工具类代码

    package com.xiaoshuai.baidu.util;  
      
    import java.io.BufferedReader;  
    import java.io.DataOutputStream;  
    import java.io.InputStreamReader;  
    import java.net.HttpURLConnection;  
    import java.net.URL;  
    import java.util.List;  
    import java.util.Map;  
      
    /** 
     * http 工具类 
     */  
    public class HttpUtil {  
      
        public static String post(String requestUrl, String accessToken, String params) throws Exception {  
            String generalUrl = requestUrl + "?access_token=" + accessToken;  
            URL url = new URL(generalUrl);  
            // 打开和URL之间的连接  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
            connection.setRequestMethod("POST");  
            // 设置通用的请求属性  
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
            connection.setRequestProperty("Connection", "Keep-Alive");  
            connection.setUseCaches(false);  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
      
            // 得到请求的输出流对象  
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());  
            out.writeBytes(params);  
            out.flush();  
            out.close();  
      
            // 建立实际的连接  
            connection.connect();  
            // 获取所有响应头字段  
            Map> headers = connection.getHeaderFields();  
            // 遍历所有的响应头字段  
            for (String key : headers.keySet()) {  
                System.out.println(key + "--->" + headers.get(key));  
            }  
            // 定义 BufferedReader输入流来读取URL的响应  
            BufferedReader in = null;  
            if (requestUrl.contains("nlp"))  
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));  
            else  
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));  
            String result = "";  
            String getLine;  
            while ((getLine = in.readLine()) != null) {  
                result += getLine;  
            }  
            in.close();  
            System.out.println("result:" + result);  
            return result;  
        }  
    }  

6.检测人脸美丑及年龄

http://ai.baidu.com/docs#    http://ai.baidu.com/docs#/Face-API/top   FACE官网文档 查看相关参数含义

   API调用代码示例
    package com.xiaoshuai.test;  
      
    import java.io.IOException;  
    import java.net.URLEncoder;  
    import java.util.HashMap;  
      
    import org.json.JSONObject;  
      
    import com.baidu.aip.face.AipFace;  
    import com.baidu.aip.http.AipRequest;  
      
    public class  Test {  
        public static void main(String[] args) throws Exception {  
                /****************/  
                String Filepath = "G:/test2.jpg";  
                String image = Base64Util.encode(FileUtil.readFileByBytes(Filepath));  
                String url = "https://aip.baidubce.com/rest/2.0/face/v1/detect";  
                String params =  URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(image, "UTF-8")+"&face_fields=age,beauty,expression,gender,glasses,race,qualities";  
                try {  
                    HttpUtil httpUtil = new HttpUtil();  
                    String result = httpUtil.post(url, "你自己获取的accessToken", params);  
                    System.out.println(result);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
        }  
    }  

7.返回JSON字符串内容

age 年龄 (目前官网还是没有说明年龄的误差范围)

beauty 美丑分数 0-100 越大值越美(之前官网写的是0-1在我发现错误时,提交官网,官网及时做了修改)

如花识别年龄38 美丑评分21 表示不太合理

{
  "result": [{
    "expression": 0,
    "face_probability": 1,
    "glasses": 0,
    "location": {
      "height": 155,
      "width": 136,
      "left": 103,
      "top": 49
    },
    "beauty": 21.201513290405,
    "race": "yellow",
    "expression_probablity": 0.77510279417038,
    "rotation_angle": 9,
    "yaw": 2.6519072055817,
    "roll": 10.0813331604,
    "qualities": {
      "completeness": 0,
      "occlusion": {
        "left_eye": 0,
        "chin": 0,
        "mouth": 0,
        "right_cheek": 0,
        "left_cheek": 0,
        "nose": 0,
        "right_eye": 0
      },
      "blur": 0,
      "type": {
        "cartoon": 0.0060238856822252,
        "human": 0.99397611618042
      },
      "illumination": 0
    },
    "gender_probability": 0.93728905916214,
    "age": 37.866649627686,
    "gender": "male",
    "glasses_probability": 0.99999260902405,
    "race_probability": 0.99436098337173,
    "pitch": -17.080112457275
  }],
  "result_num": 1,
  "log_id": 2045651588
}

以上就是百度人脸识别API的调用测试流程及demo

收藏
点赞
3
个赞
共10条回复 最后由用户已被禁言回复于2022-04
#11爱上主丽叶回复于2018-05

稳妥的先点赞收藏,然后下载项目部署研究。另外多谢大牛。

0
#10daipeng_hi回复于2017-12
#9 用户已被禁言回复
可以给帖子点赞哦

已点,哈哈

0
#9用户已被禁言回复于2017-12
#8 daipeng_hi回复
很赞

可以给帖子点赞哦

1
#8daipeng_hi回复于2017-12

很赞

0
#7笔墨哥回复于2017-11
#6 用户已被禁言回复
哈哈

继续加油,期待很多分享呢

0
#6用户已被禁言回复于2017-11
#5 笔墨哥回复
写的真不错~厉害啦~

哈哈

1
#5笔墨哥回复于2017-11

写的真不错~厉害啦~

0
#4用户已被禁言回复于2017-10

微信扫码体验哦

1
#3用户已被禁言回复于2017-10

大家是不是喜欢看有界面示例的内容

1
#2用户已被禁言回复于2017-10

SDK调用

/**
 * 基于百度SDK提供的方法进行调用
 * @author 小帅帅丶
 * @date  2017-3-20下午06:00:05
 */
public class Sample {
	public static void main(String[] args) {
        //初始化一个FaceClient
        AipFace face = new AipFace("appid","apikey","secretkey");
        //可选:设置网络连接参数
        face.setConnectionTimeoutInMillis(60000);
        face.setSocketTimeoutInMillis(60000);
        //调用API
        HashMap map = new HashMap();
        //
        map.put("face_fields", "age,beauty,expression,gender,glasses,race,qualities");
        String path = "G:/test2.jpg";
        AipRequest aipRequest = new AipRequest();
        aipRequest.setBody(map);
        JSONObject result = face.detect(FileUtil.readFileByBytes(path),map);
        System.out.println(result.toString(2));
	}
}
1
TOP
切换版块