Before API development, you need to make necessary development preparations, ensure that the Maven repository address of the HMS Core SDK has been configured in your project, and the SDK of this service has been integrated.
Create a document analyzer. You are advised to use the provided custom document recognition parameter MLDocumentSetting to specify to-be-recognized languages and other settings to create a document analyzer. In this way, you will get a higher document recognition accuracy.
- // Method 1: Use customized parameter settings.
- // Create a language set.
- List<String> languageList = new ArrayList();
- languageList.add("zh");
- languageList.add("en");
- // Set parameters.
- MLDocumentSetting setting = new MLDocumentSetting.Factory()
- // Specify the languages that can be recognized, which should comply with ISO 639-1.
- .setLanguageList(languageList)
- // Set the format of the returned text border box.
- // MLRemoteTextSetting.NGON: Return the coordinates of the four corner points of the quadrilateral.
- // MLRemoteTextSetting.ARC: Return the corner points of a polygon border in an arc. The coordinates of up to 72 corner points can be returned.
- .setBorderType(MLRemoteTextSetting.ARC)
- .create();
- MLDocumentAnalyzer analyzer =
- MLAnalyzerFactory.getInstance().getRemoteDocumentAnalyzer(setting);
- // Method 2: Use the default parameter settings to automatically detect languages for text recognition. The format of the returned text box is MLRemoteTextSetting.NGON.
- MLDocumentAnalyzer analyzer =
- MLAnalyzerFactory.getInstance().getRemoteDocumentAnalyzer();
2. Create an MLFrame using android.graphics.Bitmap. JPG, JPEG, PNG, and BMP images are supported.
- // Create an MLFrame object using the bitmap, which is the image data in bitmap format.
- MLFrame frame = MLFrame.fromBitmap(bitmap);
3. Pass the MLFrame object to the asyncAnalyseFrame method for document recognition.
- Task<MLDocument> task = analyzer.asyncAnalyseFrame(frame);
- task.addOnSuccessListener(new OnSuccessListener<MLDocument>() {
- @Override
- public void onSuccess(MLDocument document) {
- // Recognition success.
- }
- }).addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- // Recognition failure.
- // Recognition failure.
- try {
- MLException mlException = (MLException)e;
- // Obtain the result codes. You can process the result codes and customize respective messages displayed to users. For details about the result codes, please refer to MLException.
- int errorCode = mlException.getErrCode();
- // Obtain the error information. You can quickly locate the fault based on the result code.
- String errorMessage = mlException.getMessage();
- } catch (Exception error) {
- // Handle the conversion error.
- }
- }
- });
4. After the recognition is complete, stop the analyzer to release recognition resources.
- if (analyzer != null) {
- try {
- analyzer.stop();
- } catch (IOException e) {
- // Exception handling.
- }
- }