天天看點

借助百度雲中的百度人臉識别用Java開發一個人臉識别百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666

借助百度雲中的百度人臉識别用Java開發一個人臉識别百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666

百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top

擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 

人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index

人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666

借助百度雲中的百度人臉識别用Java開發一個人臉識别百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666

效果可以微信掃一掃檢視

Java調用百度的接口。

示例工程也都是調用接口的代碼

不知道為什麼好多人說看不懂

前提是自己會Java。知道JSON HTTP

代碼報錯看看JDK有沒有替換成自己本地

demo可以看我的微信小程式。裡面是用的騰訊優圖和百度人臉檢測2個接口

連結的代碼是完整的。謝謝

代碼下載下傳位址  http://download.csdn.net/download/u010651369/10117269

連結: https://pan.baidu.com/s/1ht3H9pq 密碼: uxxf 示例項目下載下傳位址

想看作者做的功能效果。可以掃上面的碼在小程式檢視或者通路

1.官網文檔必須看

http://ai.baidu.com/docs

http://aixiaoshuai.mydoc.io/

借助百度雲中的百度人臉識别用Java開發一個人臉識别百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666

2.在管理中心建立應用及檢視相關參數 AppID APIKey SecretKey都需要儲存起來

借助百度雲中的百度人臉識别用Java開發一個人臉識别百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666

3.搬磚測試

項目需要的lib包,基本下載下傳官網的SDK就都會包含。

借助百度雲中的百度人臉識别用Java開發一個人臉識别百度應用建立步驟官網圖文提供:http://ai.baidu.com/docs#/Begin/top擷取Token圖文步驟官網已提供:http://ai.baidu.com/docs#/Auth/top 人臉檢測V3線上體驗:https://www.ydxiaoshuai.cn/xai/rest/face/index人臉檢測V3(JavaAPI)示例代碼位址:http://ai.baidu.com/forum/topic/show/864666
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<String, String>(),new HashMap<String, String>());
		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<String, List<String>> 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#FACE官網文檔

請求參數

是否必選 類型 說明
image string base64編碼後的圖檔資料,圖檔大小不超過2M。
max_face_num uint32 最多處理人臉數目,預設值1
face_fields string 包括age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities資訊,逗号分隔,預設隻傳回人臉框、機率和旋轉角度。
  • URL參數:
參數
access_token 通過API Key和Secret Key擷取的access_token,參考“Access Token擷取”
  • Header如下:
參數
Content-Type application/x-www-form-urlencoded
  • Body中資料如下:
參數
image 圖像base64編碼
max_face_num 非必填,預設1
face_fields 非必填
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
}
           

8.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));
	}
}                

以上就是百度人臉識别API的調用測試流程及demo

阿裡雲人臉識别API内容很少。傳回隻有簡單的資料。不如百度的全面。

還有一點。

阿裡雲的是1分錢購買。 100000一共就這麼多請求次數。

百度不要錢,按天算請求次數。但是不保證并發。

綜上百度API可以考慮入手學習一下。絕非廣告。

開源中國與CSDN是同一個部落客不存在轉載哦

http://ai.baidu.com/forum 想了解。可以去百度的論壇咨詢

不會Java就沒必要加QQ問了

QQ:783021975