我正在使用Google的光学字符识别API为Android Studio编写应用程序。
我基本上直接从相机拍摄的照片中检索数据,以Base64编码并以低分辨率编码(产生大小为300KB的字节数组)。
我在一个线程中运行此代码以使用此base64编码图像发出请求,但服务器返回的响应有点慢(大约9-10秒)。
此外,根据Google控制台的说法,我提出的请求的平均延迟时间为1000毫秒。
是正常还是我做错了什么?有什么方法可以减少这种延迟吗?
if(getIntent().getBooleanExtra("requestDataToAPI",false)){ // Scan effectué
String[] photoBase64 = {getIntent().getStringExtra("photoBase64")};
LoadDataFromImage task = new LoadDataFromImage(this);
task.execute(photoBase64);
}
处理请求的线程:
private class LoadDataFromImage extends AsyncTask<String, Integer, String> {
private Context ctx;
public LoadDataFromImage (Context context){
ctx = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(ctx);
mDialog.setMessage("Analyse de la photo ...");
mDialog.setCancelable(false);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.show();
}
@Override
protected String doInBackground(String... photoBase64) {
Vision.Builder visionBuilder = new Vision.Builder( new NetHttpTransport(), new AndroidJsonFactory(), null);
String cleAPI = getString(R.string.google_vision_ocr_api_key); // CLE PRIVEE ---> vous DEVEZ vous procurer votre propre clé avec Google
visionBuilder.setVisionRequestInitializer(new VisionRequestInitializer(cleAPI));
vision = visionBuilder.build();
// Type d'analyse d'image
Feature desiredFeature = new Feature();
desiredFeature.setType("TEXT_DETECTION");
Image inputImage = new Image();
inputImage.encodeContent(com.google.api.client.util.Base64.decodeBase64(photoBase64[0]));
AnnotateImageRequest request = new AnnotateImageRequest();
request.setImage(inputImage);
request.setFeatures(Arrays.asList(desiredFeature));
BatchAnnotateImagesRequest batchRequest = new BatchAnnotateImagesRequest();
batchRequest.setRequests(Arrays.asList(request));
// Réponse du serveur
BatchAnnotateImagesResponse batchResponse = new BatchAnnotateImagesResponse();
try {
batchResponse = vision.images().annotate(batchRequest).execute();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Impossible d'accéder à la reconnaissance de textes", Toast.LENGTH_LONG).show();
Log.d("API Run :", e.toString());
}
final TextAnnotation text = batchResponse.getResponses().get(0).getFullTextAnnotation();
if(text != null){
String textReceived = text.getText();
System.out.println(textReceived);
return textReceived;
}
else{
return null;
}
}
protected void onProgressUpdate(Integer... progress) {
mDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mDialog.dismiss();
addName.setText(result);
Toast.makeText(getApplicationContext(), "Facture transférée", Toast.LENGTH_SHORT).show();
}
}