最近,項目中,需要百度的接口對車輛外觀損傷的資訊進行識别。之前沒做過這方面相關的,現做一個demo來學習實作一下
一、首先我們先浏覽一下百度api文檔,裡面有相關的接口介紹~(https://ai.baidu.com/docs#/ImageClassify-API/b80093c8)
二、根據文檔我們知道,在調用圖檔識别接口的時候需要先擷取access_token,文檔裡面也提供了我們擷取token的方式,稍作修改如下
package com.ljm.demo;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* 擷取token類
*/
public class AuthService {
/**
* 擷取權限token
* @return 傳回示例:
* {
* "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
* "expires_in": 2592000
* }
*/
public static String getAuth() {
// 官網擷取的 API Key 更新為你注冊的
String clientId = "uIHAhDByPdCG10O1111111";
// 官網擷取的 Secret Key 更新為你注冊的
String clientSecret = "9V9yfT1MmYboTTW111111";
return getAuth(clientId, clientSecret);
}
/**
* 擷取API通路token
* 該token有一定的有效期,需要自行管理,當失效時需重新擷取.
* @param ak - 百度雲官網擷取的 API Key
* @param sk - 百度雲官網擷取的 Securet Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
public static String getAuth(String ak, String sk) {
// 擷取token位址
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
String getAccessTokenUrl = authHost
// 1. grant_type為固定參數
+ "grant_type=client_credentials"
// 2. 官網擷取的 API Key
+ "&client_id=" + ak
// 3. 官網擷取的 Secret Key
+ "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打開和URL之間的連接配接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// 擷取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 周遊所有的響應頭字段
for (String key : map.keySet()) {
System.err.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 傳回結果示例
*/
System.err.println("result:" + result);
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("擷取token失敗!");
e.printStackTrace(System.err);
}
return null;
}
public static void main(String[] args) {
System.out.println(getAuth());
}
}
上述的ApiKey和SecretKey可登陸百度控制台檢視,第一次登陸需要建立應用:
三、執行代碼擷取access_token之後,使用http請求調用百度圖像識别接口
package com.ljm.demo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;
/**
* Created by linjiaming
*/
public class BaiduAiTest {
public static void main(String[] args) {
getBaiduAiResult();
}
public static void getBaiduAiResult() {
try {
String accessToken = "生成的token";
String postURL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_damage"
+ "?access_token=" + accessToken;
//System.out.println(postURL);
//http的 cookie 的 path 屬性不一緻,cookie中的是"baidu.com",而請求路徑path中的是"aip.baidubce.com".
RequestConfig requestConfig = RequestConfig.custom()
.setCookieSpec("aip.baidubce.com").build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(postURL);
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
List<NameValuePair> params=new ArrayList<>();
params.add(new BasicNameValuePair("image", ImageToBase64("D:\\test.jpg")));
String str= EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
// 擷取結果實體
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
//進行輸出操作 這裡就簡單的使用EntityUtils工具類的toString()方法
System.out.println(EntityUtils.toString(entity,"UTF-8"));
}
else {
EntityUtils.consume(entity);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
private static String ImageToBase64(String imgPath) {
byte[] data = null;
// 讀取圖檔位元組數組
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對位元組數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
// 傳回Base64編碼過的位元組數組字元串
//System.out.println("本地圖檔轉換Base64:" + encoder.encode(Objects.requireNonNull(data)));
return encoder.encode(Objects.requireNonNull(data));
}
}
測試圖檔:
測試結果:
{
"log_id": 7151095137225675373,
"result": {
"damage_info": [{
"parts": "後保險杠",
"type": "刮擦",
"probability": 89
}, {
"parts": "右後葉子闆",
"type": "刮擦",
"probability": 47
}]
}
}