We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All
GuidesML KitAndroidApp DevelopmentText-related ServicesText Recognition

Text Recognition

Service Introduction

The text recognition service can extract text from images of receipts, business cards, and documents. This service is useful for industries such as printing, education, and logistics. You can use it to create apps that handle data entry and check tasks.

This service can run on the cloud or device, but the supported languages differ in the two scenarios. The on-device API can recognize text in Simplified Chinese, Japanese, Korean, and Latin-based languages (including English, Spanish, Portuguese, Italian, German, French, Russian, and special characters. For details about the supported special characters, please refer to Latin Script Supported by On-device Text Recognition). The on-cloud API supports more languages such as Simplified Chinese, English, Spanish, Portuguese, Italian, German, French, Russian, Japanese, Korean, Polish, Finnish, Norwegian, Swedish, Danish, Turkish, Thai, Arabic, and Hindi.

The text recognition service is able to recognize text in both static images and dynamic camera streams with a host of APIs, which you can call synchronously or asynchronously to build your text recognition-enabled apps.

Use Cases

People may exchange their business cards in social networking, technical communications, business meetings, and many other scenarios. The text recognition service quickly recognizes key information in business cards and records them into the desired system. In the express field, this service detects images to recognize their contained information such as the recipient name, phone number, and address, and fills the information into the required places. It helps users get out of the dilemma of manually inputting text, making your apps more attractive.

Precautions

The text recognition service running on the cloud recognizes text with higher accuracy than that running on the device. However, the on-cloud one is unable to support text recognition from camera streams and cannot work in synchronous mode. If you want to use the on-cloud service of text recognition, enable ML Kit first. The text analyzer is created by different methods for text recognition from images on the device in synchronous mode, text recognition from images on the device in asynchronous mode, text recognition from images on the cloud in asynchronous mode, and text recognition from camera streams on the device. For details about how to create the text analyzer, please refer to the sample code in the development procedure.

Expand

Item

Device

Cloud

Use case

Real-time processing of images and camera streams and sparse text recognition in images

High text recognition accuracy, dense text recognition in document images, and sparse text recognition in other types of images

Supported languages

Simplified Chinese, Japanese, Korean, and Latin-based languages (including English, Spanish, Portuguese, Italian, German, French, Russian, and special characters. For details about the supported special characters, please refer to Latin Script Supported by On-device Text Recognition)

Simplified Chinese, English, Spanish, Portuguese, Italian, German, French, Russian, Japanese, Korean, Polish, Finnish, Norwegian, Swedish, Danish, Turkish, Thai, Arabic, and Hindi

Call mode

Synchronous and asynchronous

Asynchronous

Development Procedure

Before app development, you need to make necessary development preparations, configure the Maven repository address for the HMS Core SDK, and integrate the text recognition SDK.

Text Recognition from Images on the Device

  1. Create the text analyzer MLTextAnalyzer to recognize text in images. You can set MLLocalTextSetting to specify languages that can be recognized. If you do not set the languages, only Latin-based languages can be recognized by default.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 1: Use default parameter settings to configure the on-device text analyzer. Only Latin-based languages can be recognized.
    2. MLTextAnalyzer analyzer = MLAnalyzerFactory.getInstance().getLocalTextAnalyzer();
    3. // Method 2: Use the customized parameter MLLocalTextSetting to configure the text analyzer on the device.
    4. MLLocalTextSetting setting = new MLLocalTextSetting.Factory()
    5. .setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE)
    6. // Specify languages that can be recognized.
    7. .setLanguage("zh")
    8. .create();
    9. MLTextAnalyzer analyzer = MLAnalyzerFactory.getInstance().getLocalTextAnalyzer(setting);
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 1: Use default parameter settings to configure the on-device text analyzer. Only Latin-based languages can be recognized.
    2. val analyzer = MLAnalyzerFactory.getInstance().localTextAnalyzer
    3. // Method 2: Use the customized parameter MLLocalTextSetting to configure the text analyzer on the device.
    4. val setting = MLLocalTextSetting.Factory()
    5. .setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE) // Set languages that can be recognized.
    6. .setLanguage("zh")
    7. .create()
    8. val analyzer = MLAnalyzerFactory.getInstance().getLocalTextAnalyzer(setting)
  1. Create an MLFrame object using android.graphics.Bitmap. JPG, JPEG, PNG, and BMP images are supported. It is recommended that the length-width ratio range from 1:2 to 2:1.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Create an MLFrame object using the bitmap, which is the image data in bitmap format.
    2. MLFrame frame = MLFrame.fromBitmap(bitmap);
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Create an MLFrame object using the bitmap, which is the image data in bitmap format.
    2. val frame = MLFrame.fromBitmap(bitmap)
  1. Pass the MLFrame object to the asyncAnalyseFrame method for text recognition.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. Task<MLText> task = analyzer.asyncAnalyseFrame(frame);
    2. task.addOnSuccessListener(new OnSuccessListener<MLText>() {
    3. @Override
    4. public void onSuccess(MLText text) {
    5. // Processing for successful recognition.
    6. }
    7. }).addOnFailureListener(new OnFailureListener() {
    8. @Override
    9. public void onFailure(Exception e) {
    10. // Processing logic for recognition failure.
    11. }
    12. });
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. val task = analyzer.asyncAnalyseFrame(frame)
    2. task.addOnSuccessListener {
    3. // Processing for successful recognition.
    4. }.addOnFailureListener {
    5. // Processing logic for recognition failure.
    6. }

    The sample code uses the asynchronous call mode. Local text recognition also supports synchronous call using analyseFrame. The recognition result is specified by the MLText.Block array.

    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. Context context = getApplicationContext();
    2. MLTextAnalyzer analyzer = new MLTextAnalyzer.Factory(context).setLocalOCRMode(MLLocalTextSetting.OCR_DETECT_MODE).setLanguage("zh").create();
    3. SparseArray<MLText.Block> blocks = analyzer.analyseFrame(frame);
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. val context = applicationContext
    2. val analyzer = MLTextAnalyzer.Factory(context).setLocalOCRMode(MLLocalTextSetting.OCR_DETECT_MODE).setLanguage("zh").create()
    3. val blocks = analyzer!!.analyseFrame(frame)
  2. After the recognition is complete, stop the analyzer to release recognition resources.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. try {
    2. if (analyzer != null) {
    3. analyzer.stop();
    4. }
    5. } catch (IOException e) {
    6. // Exception handling.
    7. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. try {
    2. if (analyzer != null) {
    3. analyzer.stop()
    4. }
    5. } catch (e: IOException) {
    6. // Exception handling.
    7. }

Text Recognition from Images on the Cloud

  1. Set authentication information for your app. For details, please refer to Notes on Using Cloud Authentication Information.
  2. Create an analyzer. The recommended way is to using MLRemoteTextSetting. In this way, you can specify to-be-recognized languages for more accurate text recognition.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 1: Use customized parameter settings.
    2. // Create a language set.
    3. List<String> languageList = new ArrayList();
    4. languageList.add("zh");
    5. languageList.add("en");
    6. // Set parameters.
    7. MLRemoteTextSetting setting = new MLRemoteTextSetting.Factory()
    8. // Set the font type for the on-cloud API of text recognition.
    9. // When handwriting is set, only sparse text is supported as the detection mode, only Chinese (zh) is supported in the language list, and only the coordinates of four corner points of the quadrilateral are supported as the format of the returned text border box.
    10. // Configurations set via methods like setTextDensityScene, setLnaguageList, and setBorderType do not take effect.
    11. // When printscript is set, manually configure the language list, detection mode, and format of the returned text border box. If not, their default configurations will be adopted automatically.
    12. // MLRemoteTextSetting.OCR_HANDWRITTENFONT_SCENE: handwriting.
    13. // MLRemoteTextSetting.OCR_PRINTFONT_SCENE: printscript.
    14. .setTextFontScene(MLRemoteTextSetting.OCR_HANDWRITTENFONT_SCENE)
    15. // Set the on-cloud text detection mode.
    16. // MLRemoteTextSetting.OCR_COMPACT_SCENE: dense text recognition.
    17. // MLRemoteTextSetting.OCR_LOOSE_SCENE: sparse text recognition.
    18. .setTextDensityScene(MLRemoteTextSetting.OCR_LOOSE_SCENE)
    19. // Specify the languages that can be recognized, which should comply with ISO 639-1.
    20. .setLanguageList(languageList)
    21. // Set the format of the returned text border box.
    22. // MLRemoteTextSetting.NGON: Return the coordinates of the four corner points of the quadrilateral.
    23. // MLRemoteTextSetting.ARC: Return the corner points of a polygon border in an arc. The coordinates of up to 72 corner points can be returned.
    24. .setBorderType(MLRemoteTextSetting.ARC)
    25. .create();
    26. MLTextAnalyzer analyzer = MLAnalyzerFactory.getInstance().getRemoteTextAnalyzer(setting);
    27. // Method 2: Use the default parameter settings to automatically detect languages for text recognition. This method is applicable to sparse text scenarios. The format of the returned text box is MLRemoteTextSetting.NGON.
    28. MLTextAnalyzer analyzer = MLAnalyzerFactory.getInstance().getRemoteTextAnalyzer();
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 1: Use customized parameter settings.
    2. // Create a language set.
    3. val languageList: MutableList<String?> = ArrayList< String?>()
    4. languageList.add("zh")
    5. languageList.add("en")
    6. // Set parameters.
    7. val setting = MLRemoteTextSetting.Factory() // Set the on-cloud text detection mode:
    8. // MLRemoteTextSetting.OCR_COMPACT_SCENE: dense text recognition
    9. // MLRemoteTextSetting.OCR_LOOSE_SCENE: sparse text recognition
    10. .setTextDensityScene(MLRemoteTextSetting.OCR_LOOSE_SCENE) // Specify the languages that can be recognized, which should comply with ISO 639-1.
    11. .setLanguageList(languageList) // Set the format of the returned text border box.
    12. // MLRemoteTextSetting.NGON: Return the coordinates of the four corner points of the quadrilateral.
    13. // MLRemoteTextSetting.ARC: Return the corner points of a polygon border in an arc. The coordinates of up to 72 corner points can be returned.
    14. .setBorderType(MLRemoteTextSetting.ARC)
    15. .create()
    16. val analyzer = MLAnalyzerFactory.getInstance().getRemoteTextAnalyzer(setting)
    17. // Method 2: Use the default parameter settings to automatically detect languages for text recognition. This method is applicable to sparse text scenarios. The format of the returned text box is MLRemoteTextSetting.NGON.
    18. val analyzer = MLAnalyzerFactory.getInstance().remoteTextAnalyzer
  3. Create an MLFrame object using android.graphics.Bitmap. JPG, JPEG, PNG, and BMP images are supported.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. MLFrame frame = MLFrame.fromBitmap(bitmap);
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. val frame = MLFrame.fromBitmap(bitmap)
  4. Pass the created MLFrame object to the asyncAnalyseFrame method of the analyzer for text recognition. For details about the result codes, please refer to MLException.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. Task<MLText> task = analyzer.asyncAnalyseFrame(frame);
    2. task.addOnSuccessListener(new OnSuccessListener<MLText>() {
    3. @Override
    4. public void onSuccess(MLText text) {
    5. // Recognition success.
    6. }
    7. }).addOnFailureListener(new OnFailureListener() {
    8. @Override
    9. public void onFailure(Exception e) {
    10. // If the recognition fails, obtain related exception information.
    11. try {
    12. MLException mlException = (MLException) e;
    13. // Obtain the result code. You can process the result code and customize respective messages displayed to users.
    14. int errorCode = mlException.getErrCode();
    15. // Obtain the error information. You can quickly locate the fault based on the result code.
    16. String errorMessage = mlException.getMessage();
    17. } catch (Exception error) {
    18. // Handle the conversion error.
    19. }
    20. }
    21. });
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. val task = analyzer!!.asyncAnalyseFrame(frame)
    2. task.addOnSuccessListener {
    3. // Recognition success.
    4. }.addOnFailureListener { e ->
    5. // If the recognition fails, obtain related exception information.
    6. try {
    7. val mlException = e as MLException
    8. // Obtain the result code. You can process the result code and customize respective messages displayed to users.
    9. val errorCode = mlException.errCode
    10. // Obtain the error information. You can quickly locate the fault based on the result code.
    11. val errorMessage = mlException.message
    12. } catch (error: Exception) {
    13. // Handle the conversion error.
    14. }
    15. }
  5. After the recognition is complete, stop the analyzer to release recognition resources.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. if (analyzer != null) {
    2. try {
    3. analyzer.stop();
    4. } catch (IOException e) {
    5. // Exception handling.
    6. }
    7. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. if (analyzer != null) {
    2. try {
    3. analyzer.stop()
    4. } catch (e: IOException) {
    5. // Exception handling.
    6. }
    7. }

Text Recognition from Camera Streams on the Device

Your app can process camera streams, convert camera frames into the MLFrame object, and recognize text using the local static image recognition method. If the synchronous recognition API is called, your app can also use the LensEngine class built in the SDK to locally detect text in camera streams and create and initialize a LensEngine object. For details, please refer to the sample code:

  1. Create an analyzer.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 1: Use default parameter settings to configure the text analyzer. Only Latin-based languages can be recognized.
    2. MLTextAnalyzer analyzer = new MLTextAnalyzer.Factory(context).create();
    3. // Method 2: Use the custom parameter MLTextAnalyzer.Factory to configure the text analyzer. Other supported languages can be recognized.
    4. MLTextAnalyzer.Factory factory = new MLTextAnalyzer.Factory(context);
    5. // Specify languages that can be recognized.
    6. factory.setLanguage("zh");
    7. MLTextAnalyzer analyzer = factory.create();
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. // Method 1: Use default parameter settings to configure the text analyzer. Only Latin-based languages can be recognized.
    2. val analyzer = MLTextAnalyzer.Factory(context).create()
    3. // Method 2: Use the custom parameter MLTextAnalyzer.Factory to configure the text analyzer. Other supported languages can be recognized.
    4. val factory = MLTextAnalyzer.Factory(context)
    5. // Specify languages that can be recognized.
    6. factory.setLanguage("zh")
    7. val analyzer = factory.create()
  2. Create the OcrDetectorProcessor class for processing recognition results. This class implements the MLAnalyzer.MLTransactor<T> API and uses the transactResult method in this class to obtain the recognition results and implement specific services.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. public class OcrDetectorProcessor implements MLAnalyzer.MLTransactor<MLText.Block> {
    2. @Override
    3. public void transactResult(MLAnalyzer.Result<MLText.Block> results) {
    4. SparseArray<MLText.Block> items = results.getAnalyseList();
    5. // Determine detection result processing as required. Note that only the detection results are processed.
    6. // Other detection-related APIs provided by ML Kit cannot be called.
    7. }
    8. @Override
    9. public void destroy() {
    10. // Callback method used to release resources when the detection ends.
    11. }
    12. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. class OcrDetectorProcessor : MLTransactor<MLText.Block?> {
    2. override fun transactResult(results: MLAnalyzer.Result<MLText.Block?>) {
    3. val items = results.analyseList
    4. // Determine detection result processing as required. Note that only the detection results are processed.
    5. // Other detection-related APIs provided by ML Kit cannot be called.
    6. }
    7. override fun destroy() {
    8. // Callback method used to release resources when the detection ends.
    9. }
    10. }
  3. Set the detection result processor to bind the analyzer to the result processor.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. analyzer.setTransactor(new OcrDetectorProcessor());
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. analyzer!!.setTransactor(OcrDetectorProcessor())
  4. Call the synchronous API to use the built-in LensEngine of the SDK to create an object, register the analyzer, and initialize camera parameters.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. LensEngine lensEngine = new LensEngine.Creator(getApplicationContext(),analyzer)
    2. .setLensType(LensEngine.BACK_LENS)
    3. .applyDisplayDimension(1440, 1080)
    4. .applyFps(30.0f)
    5. .enableAutomaticFocus(true)
    6. .create();
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. val lensEngine = LensEngine.Creator(applicationContext, analyzer)
    2. .setLensType(LensEngine.BACK_LENS)
    3. .applyDisplayDimension(1440, 1080)
    4. .applyFps(30.0f)
    5. .enableAutomaticFocus(true)
    6. .create()
  5. Call the run method to launch the camera, read camera streams, and perform recognition. (For details, please refer to the sample code to implement other logic of the SurfaceView control.)
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. SurfaceView mSurfaceView = findViewById(R.id.surface_view);
    2. try {
    3. lensEngine.run(mSurfaceView.getHolder());
    4. } catch (IOException e) {
    5. // Exception handling logic.
    6. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. val mSurfaceView: SurfaceView? = findViewById(R.id.surface_view);
    2. try {
    3. lensEngine!!.run(mSurfaceView!!.holder)
    4. } catch (e: IOException) {
    5. // Exception handling logic.
    6. }
  6. After the detection is complete, stop the analyzer to release detection resources.
    Java
    Kotlin
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. if (analyzer != null) {
    2. try {
    3. analyzer.stop();
    4. } catch (IOException e) {
    5. // Exception handling.
    6. }
    7. }
    8. if (lensEngine != null) {
    9. lensEngine.release();
    10. }
    Collapse
    Word wrap
    Dark theme
    Copy code
    1. if (analyzer != null) {
    2. try {
    3. analyzer.stop()
    4. } catch (e: IOException) {
    5. // Exception handling.
    6. }
    7. }
    8. lensEngine?.release()

In camera stream detection, when MLAnalyzer.MLTransactor<T> is inherited to process detection results, if your app needs to stop detection after a specific result is detected and continue detection after the result is processed, please refer to Development for Multi Detections in Camera Stream Detection Mode.

Search
Enter a keyword.