本文介紹了如何使用Java SDK圖片OCR介面,識別圖片中的文字資訊。
前提條件
安裝Java依賴。關於安裝Java依賴的具體操作,請參見安裝Java依賴。
說明請一定按照安裝Java依賴頁面中的版本安裝,否則會導致調用失敗。
如果使用本地檔案或者二進位檔案檢測,請下載並在專案工程中引入Extension.Uploader工具類。
提交圖片同步檢測任務
介面 | 描述 | 支援的Region |
ImageSyncScanRequest | 提交圖片OCR同步識別任務,對圖片中的文字進行識別(scene=ocr)。 |
|
範例程式碼
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
/**
* 阿里雲帳號AccessKey擁有所有API的存取權限,建議您使用RAM使用者進行API訪問或日常營運。
* 常見擷取環境變數方式:
* 方式一:
* 擷取RAM使用者AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* 擷取RAM使用者AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* 方式二:
* 擷取RAM使用者AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* 擷取RAM使用者AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
DefaultProfile profile = DefaultProfile.getProfile(
"cn-shanghai",
"建議從環境變數中擷取RAM使用者AccessKey ID",
"建議從環境變數中擷取RAM使用者AccessKey Secret");
DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
IAcsClient client = new DefaultAcsClient(profile);
ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
// 指定返回格式。
imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
// 指定要求方法。
imageSyncScanRequest.setMethod(MethodType.POST);
imageSyncScanRequest.setEncoding("utf-8");
// 支援HTTP和HTTPS。
imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
JSONObject httpBody = new JSONObject();
/**
* 設定要檢測的情境。
* ocr:表示OCR圖文識別。
*/
httpBody.put("scenes", Arrays.asList("ocr"));
/**
* 設定待檢測的圖片,一張圖片對應一個檢測任務。
* 多張圖片同時檢測時,處理時間由最後一張處理完的圖片決定。
* 通常情況下批量檢測的平均回應時間比單任務檢測長,一次批量提交的圖片數越多,回應時間被拉長的機率越高。
* 代碼中以單張圖片檢測作為樣本,如果需要批量檢測多張圖片,請自行構建多個任務。
*/
JSONObject task = new JSONObject();
task.put("dataId", UUID.randomUUID().toString());
// 設定圖片連結。
task.put("url", "https://example.com/xxx.jpg");
httpBody.put("tasks", Arrays.asList(task));
imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()), "UTF-8", FormatType.JSON);
/**
* 請設定逾時時間。服務端全鏈路處理逾時時間為10秒,請據此做相應設定。
* 如果您設定的ReadTimeout小於服務端處理的時間,程式中會獲得一個read timeout異常。
*/
imageSyncScanRequest.setConnectTimeout(3000);
imageSyncScanRequest.setReadTimeout(10000);
HttpResponse httpResponse = null;
try {
httpResponse = client.doAction(imageSyncScanRequest);
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
// 服務端接收到請求,並完成處理返回的結果。
if(httpResponse != null && httpResponse.isSuccess()){
JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
System.out.println(JSON.toJSONString(scrResponse));
int requestCode = scrResponse.getIntValue("code");
// 每一張圖片的檢測結果。
JSONArray taskResults = scrResponse.getJSONArray("data");
if (200 == requestCode) {
for (Object taskResult : taskResults) {
// 單張圖片的處理結果。
int taskCode = ((JSONObject)taskResult).getIntValue("code");
// 對應檢測情境下,圖片的處理結果。如果是多個情境,則會有每個情境的結果。
JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
if(200 == taskCode){
for (Object sceneResult : sceneResults) {
String scene = ((JSONObject)sceneResult).getString("scene");
String suggestion = ((JSONObject)sceneResult).getString("suggestion");
//do something
// 識別出來的文字資訊。
if("review" .equals(suggestion) && "ocr".equals(scene)){
JSONObject idCardInfo = ((JSONObject) sceneResult).getJSONObject("idCardInfo");
System.out.println(idCardInfo.toJSONString());
}
}
}else{
// 單張圖片處理失敗,原因視具體的情況詳細分析。
System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
}
}
} else {
/**
* 表明請求整體處理失敗,原因視具體的情況詳細分析。
*/
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
}
}
}
}