我一直在使用 Google Vision api 扫描图片中的文字并将其显示在TextView 中,唯一的问题是它是否在图片中检测到4个或更多TextBlocks块出现乱序。我一直在寻找解决问题的方法,但到目前为止还找不到任何帮助,非常感谢任何帮助。
以下是我翻译图片的代码:
public void RunOCR(TextView scanResults, Context context) {
detector = new TextRecognizer.Builder(context).build();
imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/pic.jpg"));
try {
Bitmap bitmap = decodeBitmapUri(context, imageUri);
if (detector.isOperational() && bitmap != null) {
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> textBlocks = detector.detect(frame);
String blocks = "";
String lines = "";
String words = "";
int number = 0;
boolean goneThroughLoop = false;
//if(textBlocks.size() >= 4){number = textBlocks.size() - 2;}
for (int index = number; index < textBlocks.size(); index++) {
//extract scanned text blocks here
if(index == textBlocks.size() - 2 && goneThroughLoop){break;}
TextBlock tBlock = textBlocks.valueAt(index);
blocks = blocks + tBlock.getValue() + "\n" + "\n";
for (Text line : tBlock.getComponents()) {
//extract scanned text lines here
lines = lines + line.getValue() + "\n";
for (Text element : line.getComponents()) {
//extract scanned text words here
words = words + element.getValue() + ", ";
}
}
/*if(index == textBlocks.size() - 1 && !goneThroughLoop){index = 0; goneThroughLoop = true; ;
tBlock = textBlocks.valueAt(index);
blocks = blocks + tBlock.getValue() + "\n" + "\n";
for (Text line : tBlock.getComponents()) {
//extract scanned text lines here
lines = lines + line.getValue() + "\n";
for (Text element : line.getComponents()) {
//extract scanned text words here
words = words + element.getValue() + ", ";
}
}*/
}
}
if (textBlocks.size() == 0) {
scanResults.setText("Scan Failed: Found nothing to scan");
} else {
scanResults.setText(scanResults.getText() + blocks + "\n");
}
} else {
scanResults.setText("Could not set up the detector!");
}
} catch (Exception e) {
//Toast.makeText(this, "Failed to load Image", Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, e.toString());
}
}
编辑:最近修复使用if语句(在代码中注释掉)重新排列块不再有效。下面的链接是我遇到的问题的截图。