微軟認知服務-Computer Vision API呼叫合集
阿新 • • 發佈:2018-11-11
import java.io.File; import java.io.InputStream; import java.math.BigDecimal; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * * 這個類主要是微軟認知服務中的計算機視覺 * * * @author liuyb * */ public class CognitiveUtils { public static final String KEY = "申請的微軟的key"; // 影象分析的連結 public static final String ANALYZE_IMAGE = "https://api.projectoxford.ai/vision/v1.0/analyze"; // 描述影象的連結 public static final String DESCRIBE_IMAGE = "https://api.projectoxford.ai/vision/v1.0/describe"; // 獲取縮圖的連結 public static final String GET_THUMBNAIL = "https://api.projectoxford.ai/vision/v1.0/generateThumbnail"; // 特定領域模型識別(現在只支援名人識別,這個常量支援兩個介面) public static final String Domain_SPECIFIC = "https://api.projectoxford.ai/vision/v1.0/models"; // 識別圖片中的文字 public static final String OCR = "https://api.projectoxford.ai/vision/v1.0/ocr"; // 獲取圖片的標籤 public static final String IMAGE_TAG = "https://api.projectoxford.ai/vision/v1.0/tag"; public static HttpClient httpclient = HttpClients.createDefault(); // 呼叫微軟認知服務獲取資料 /** * 分析圖片的介面 * * @param filePath */ public static JSONObject analyzeImage(String filePath) { try { URIBuilder builder = new URIBuilder(ANALYZE_IMAGE); // 為連結配置的一些引數 /* * 影象特徵點: Categories:種類 ImageType:圖片型別 Faces:人臉描述 Adult:監測成人內容 * Color:顏色 Tags:標籤 Description:用一句完成的英文描述圖片 */ builder.setParameter("visualFeatures", "Description"); /* * 對一些特定領域的細節的返回 目前只支援“名人”識別:Celebrities */ // builder.setParameter("details", "{string}"); /* * 以哪種語言返回,預設為英語 en 英文 zh 中文 */ // builder.setParameter("language", "en"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); /** * 請求型別 json application/json 圖片以url方式傳送 二進位制流 * application/octet-stream 圖片以二進位制流傳送 多檔案傳送 multipart/form-data * 圖片以二進位制流進行傳送 */ // request.setHeader("Content-Type", "application/json"); // 以json方式訪問,圖片路徑需要為一個能訪問到的地址 request.setHeader("Content-Type", "application/octet-stream"); // 以位進位制檔案流的方式訪問,圖片需要轉化成一個二進位制的流 // 還有一種請求方式multipart/form-data /* * 請求API的祕鑰(需要去微軟官方申請) */ request.setHeader("Ocp-Apim-Subscription-Key", KEY); File file = new File(filePath); if (!file.exists()) { System.out.println("圖片不存在"); return null; } // Request body // 以json方式訪問時傳遞的是一個json字串 // StringEntity reqEntity = new StringEntity("{\"Url\": // \""+filePath+"\"}"); // 以檔案流方式訪問時傳遞的是一個檔案(最終會以位二進位制進行請求) FileEntity reqEntity = new FileEntity(file); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity); System.out.println(); return (JSONObject) JSONObject.parse(result); } } catch (Exception e) { System.out.println(e.getMessage()); } return null; } /** * 描述圖片 * * @param filePath */ public static void describeImage(String filePath) { try { URIBuilder builder = new URIBuilder(DESCRIBE_IMAGE); // 最大數量的候選人描述返回。預設值是1。如果是1,則返回可信度最高的結果 builder.setParameter("maxCandidates", "1"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); // application/json application/octet-stream multipart/form-data request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", KEY); // Request body StringEntity reqEntity = new StringEntity("{\"Url\": \"" + filePath + "\"}"); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } catch (Exception e) { System.out.println(e.getMessage()); } } /** * 獲取縮圖 * * @param filePath * 原始檔案的url * @param endPath * 縮圖的url */ public static void getThumbnail(String filePath, String endPath) { try { URIBuilder builder = new URIBuilder(GET_THUMBNAIL); builder.setParameter("width", "200"); builder.setParameter("height", "200"); builder.setParameter("smartCropping", "true"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", KEY); // Request body StringEntity reqEntity = new StringEntity("{\"Url\": \"" + filePath + "\"}"); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); // 將返回的圖片輸出 IOUtils.outputImg(inputStream, endPath); } catch (Exception e) { System.out.println(e.getMessage()); } } /** * 獲取特定領域模型列表(當前微軟的API僅支援名人識別) * * @param filePath */ public static JSONObject getListDomainSpecificModels() { try { URIBuilder builder = new URIBuilder(Domain_SPECIFIC); URI uri = builder.build(); HttpGet request = new HttpGet(uri); request.setHeader("Ocp-Apim-Subscription-Key", KEY); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); String modelJson = EntityUtils.toString(entity); if (entity != null) { // System.out.println(modelJson); return (JSONObject) JSONObject.parse(modelJson); } } catch (Exception e) { System.out.println(e.getMessage()); } return null; } /** * 識別特定領域的內容(當前只支援名人識別),需要上一個介面getListDomainSpecificModels的支援 * * @param filePath */ public static void recognizeDomainSpecificContent(String filePath) { // 首先從特定領域模型列表中選取需要的領域模型 JSONObject modelJson = getListDomainSpecificModels(); // 獲取領域模型陣列 JSONArray model = (JSONArray) modelJson.get("models"); // 遍歷領域模型並找到與圖片的領域相關資訊 for (Object modelObj : model) { JSONObject json = (JSONObject) modelObj; String modelName = json.getString("name"); recognizeDomainSpecificContent(modelName, filePath); } } /** * 過載函式,用於識別給定領域的與圖片相關的資訊 * * @param modelName * @param filePath */ public static void recognizeDomainSpecificContent(String modelName, String filePath) { String modelUrl = Domain_SPECIFIC + "/" + modelName + "/analyze"; try { URIBuilder builder = new URIBuilder(modelUrl); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", KEY); // Request body StringEntity reqEntity = new StringEntity("{\"Url\":\"" + filePath + "\"}"); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } catch (Exception e) { System.out.println(e.getMessage()); } } /** * 獲取圖片中的文字資訊 * * @param filePath */ public static JSONObject OCR(String filePath, String language) { try { URIBuilder builder = new URIBuilder(OCR); /** * 語言支援: unk (AutoDetect) -- 預設 zh-Hans (ChineseSimplified) zh-Hant * (ChineseTraditional) cs (Czech) da (Danish) nl (Dutch) en * (English) fi (Finnish) fr (French) de (German) el (Greek) hu * (Hungarian) it (Italian) Ja (Japanese) ko (Korean) nb (Norwegian) * pl (Polish) pt (Portuguese, ru (Russian) es (Spanish) sv * (Swedish) tr (Turkish) */ builder.setParameter("language", language); // 是否檢測影象中的文字定位 true false builder.setParameter("detectOrientation ", "true"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); // request.setHeader("Content-Type", "application/json"); request.setHeader("Content-Type", "application/octet-stream"); request.setHeader("Ocp-Apim-Subscription-Key", KEY); // Request body // StringEntity reqEntity = new StringEntity("{\"Url\":\"" + // filePath + "\"}"); // request.setEntity(reqEntity); File localFile = new File(filePath); if (!localFile.exists()) { System.out.println("圖片不存在"); return null; } // 傳送本地圖片 // 以檔案流方式訪問時傳遞的是一個檔案(最終會以位二進位制進行請求) FileEntity reqEntity = new FileEntity(localFile); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); // HttpResponse response = httpclient.execute(request); // HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity); System.out.println(); return (JSONObject) JSONObject.parse(result); } } catch (Exception e) { System.out.println(e.getMessage()); } return null; } /** * 獲取圖片的標籤 * * @param filePath */ public static JSONObject getImgTag(String filePath) { try { URIBuilder builder = new URIBuilder(IMAGE_TAG); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/octet-stream"); request.setHeader("Ocp-Apim-Subscription-Key", KEY); File localFile = new File(filePath); if (!localFile.exists()) { System.out.println("圖片不存在"); return null; } // Request body // StringEntity reqEntity = new StringEntity("{\"Url\":\"" + // filePath + "\"}"); // request.setEntity(reqEntity); FileEntity reqEntity = new FileEntity(localFile); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); return (JSONObject) JSONObject.parse(result); } catch (Exception e) { System.out.println(e.getMessage()); } return null; } }
注意:呼叫時需要httpclient的jar包的支援