OCR quick start

更新时间:
复制 MD 格式

This topic describes how to get started with the Optical Character Recognition (OCR) service.

Workflow

image
Important

When you use the Experience Center or an SDK to call the Optical Character Recognition (OCR) service, the service only recognizes the image and returns the result. It does not store your images or the recognition results.

Try the service without logging in

If you are new to the Optical Character Recognition (OCR) service, we recommend first trying it in the Alibaba Cloud OCR Experience Center, which does not require an Alibaba Cloud account. In the Experience Center, you can use the visual interface to upload a single image and test the OCR performance. All OCR services are available for an unlimited number of free trials.

If the Optical Character Recognition (OCR) service meets your business needs, go to the Optical Character Recognition (OCR) console to enable the service as needed.

Account creation and verification

  1. On the Alibaba Cloud official website, click Sign Up in the upper-right corner.

  2. On the Create an Account page, follow the on-screen instructions to create an account.

    Important

    Your Alibaba Cloud account is used to manage and pay for all your resources. This account has full permissions over all the resources it owns.

    To keep your account secure, do not share it with others and update your password regularly.

  3. Complete real-name verification for your Alibaba Cloud account.

    You must complete real-name verification to purchase and use Alibaba Cloud products.

    1. Go to the Account Management page.

    2. In the left-side navigation pane, click Real-name Verification, and follow the on-screen instructions to complete the real-name verification for your account.

Enable the service

Log in to the Optical Character Recognition (OCR) console with your Alibaba Cloud account (master account) or a RAM user (sub-account) to enable services as needed.

By default, each OCR service has a concurrency limit of 10 QPS. In the service list, you can find more details by clicking Free Trial, View Pricing, and Product Documentation.

The Optical Character Recognition (OCR) product offers nine categories of OCR services. Each service must be enabled separately, and enabling a service does not incur fees. Depending on the service you enable, you receive a free trial of either 200 calls per month or a one-time grant of 50 calls. Each successful API call consumes one call from your free trial. After the free trial is used up, you are charged based on your usage.

A RAM user is created and authorized by an Alibaba Cloud account. You must ensure that the RAM user has the AliyunOCRFullAccess and AliyunBSSContractFullAccess permissions. Otherwise, you cannot use this account to activate the service.

Note

Go to the RAM Permission List to view the permissions that a RAM user has.

Next, you can integrate the SDK into your business system and use the free trial to batch-test the OCR performance.

Test API calls

Before you integrate the SDK, we recommend using OpenAPI Explorer to call the OCR API online. OpenAPI Explorer provides sample SDK code in multiple languages and dependency information to help you understand the API call flow and simplify subsequent integration.

Use the SDK

This section uses ID card recognition with the Unified OCR service as an example to demonstrate how to integrate and use the SDK.

The structured response fields for ID card OCR include address, ethnicity, sex (gender), name, idNumber (ID number), and birthDate (date of birth), as well as quality detection fields such as isCopy (whether the image is a photocopy), isReshoot (whether the image is a recaptured photo), completenessScore, qualityScore, and tamperScore.

Get an AccessKey

Before you integrate the SDK, make sure you have obtained an AccessKey. When you use an SDK to call an Alibaba Cloud service, the request includes an AccessKey ID and an AccessKey Secret. The SDK uses them to sign the request to authenticate your identity and validate the request.

  1. In the upper-right corner of the console, hover over your account avatar and click AccessKey Management.

  2. On the AccessKey page, view your AccessKey information.

    The AccessKey list includes the AccessKey ID, Status, Last Used Cloud Service/Time, Creation Time, and Actions columns. The Actions column provides options such as Enable, Delete, and Rotate Recommended, which you can use to check if you have an enabled AccessKey.

    If the AccessKey list is empty or you do not have an enabled AccessKey, see Create an AccessKey.

Configure environment variables

We recommend that you store your AccessKey in an environment variable instead of hardcoding it in your code. This reduces the risk of AccessKey leaks.

Windows

On Windows, you can configure environment variables by using CMD or PowerShell, or by editing system properties.

CMD

Permanent

If you want an environment variable to be available in all new sessions for the current user, follow these steps.

  1. Run the following commands in CMD.

    # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
    setx ALIBABA_CLOUD_ACCESS_KEY_ID <access_key_id>
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET <access_key_secret>
  2. Open a new CMD window.

  3. In the new CMD window, run the following commands to verify that the environment variables are set.

    echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
    echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

Temporary

If you want an environment variable to be available only for the current session, run the following commands in CMD.

# Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
set ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>

You can run the following commands in the current session to verify that the environment variables are set.

echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
PowerShell

Permanent

If you want an environment variable to be available in all new sessions for the current user, follow these steps.

  1. Run the following commands in PowerShell.

    # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
    [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", "<access_key_id>", [EnvironmentVariableTarget]::User)
    [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "<access_key_secret>", [EnvironmentVariableTarget]::User)
  2. Open a new PowerShell window.

  3. In the new PowerShell window, run the following commands to verify that the environment variables are set.

    echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

Temporary

If you want an environment variable to be available only for the current session, run the following commands in PowerShell.

# Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "<access_key_id>"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "<access_key_secret>"

You can run the following commands in the current session to verify that the environment variables are set.

echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET
System properties
  • Right-click This PC and select Properties. This opens the Settings window. Click Advanced system settings to open the System Properties window.

  • In the System Properties window, select the Advanced tab, and click Environment Variables to open the Environment Variables window.

    The Environment Variables... button is at the bottom of the Advanced tab.

  • In the System variables section, click New to open the New System Variable dialog box.

  • In the Variable name field, enter ALIBABA_CLOUD_ACCESS_KEY_ID, and in the Variable value field, enter your<access_key_id>. Repeat this process for ALIBABA_CLOUD_ACCESS_KEY_SECRET and your<access_key_secret>.

After entering the values, click OK in all three windows to close them. The environment variables are now configured.

You can run the following commands in a terminal to verify that the environment variables are set.

echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

macOS

Permanent

If you want an environment variable to be available in all new sessions for the current user, add a permanent environment variable.

  1. Run the following command in a terminal to check your default shell type.

    echo $SHELL
  2. Proceed based on your default shell type.

    Zsh

    1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

      # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
      echo "export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>" >> ~/.zshrc
      echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>" >> ~/.zshrc

      Alternatively, you can manually edit the ~/.zshrc file.

      Manual modification

      Run the following command to open the shell configuration file.

      nano ~/.zshrc

      Add the following content to the configuration file.

      # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>

      In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file.

    2. Run the following command to apply the changes.

      source ~/.zshrc
    3. Open a new terminal window and run the following commands to verify that the environment variables are set.

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

    Bash

    1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

      # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
      echo "export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>" >> ~/.bash_profile
      echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>" >> ~/.bash_profile

      Alternatively, you can manually edit the ~/.bash_profile file.

      Manual modification

      Run the following command to open the shell configuration file.

      nano ~/.bash_profile

      Add the following content to the configuration file.

      # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>

      In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file.

    2. Run the following command to apply the changes.

      source ~/.bash_profile
    3. Open a new terminal window and run the following commands to verify that the environment variables are set.

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
Temporary

If you want an environment variable to be available only for the current session, add a temporary environment variable.

  1. Run the following commands.

    # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  2. Run the following commands to verify that the environment variables are set.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

Linux

Permanent

If you want an environment variable to be available in all new sessions for the current user, add a permanent environment variable.

  1. Run the following commands to append the environment variable settings to the ~/.bashrc file.

    # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
    echo "export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>" >> ~/.bashrc
    echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>" >> ~/.bashrc

    Alternatively, you can manually edit the ~/.bashrc file.

    Manual modification

    Run the following command to open the ~/.bashrc file.

    nano ~/.bashrc

    Add the following content to the configuration file.

    # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>

    In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file.

  2. Run the following command to apply the changes.

    source ~/.bashrc
  3. Open a new terminal window and run the following commands to verify that the environment variables are set.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
Temporary

If you want an environment variable to be available only for the current session, add a temporary environment variable.

  1. Run the following commands.

    # Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey Secret.
    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  2. Run the following commands to verify that the environment variables are set.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

Choose a programming language

Choose your preferred language to call the OCR API.

Java

Step 1: Configure the Java environment

Check Java environment

Run the following command in a terminal to check if Java is installed in your current environment:

java -version

Java 8 or a later version is required. You can confirm the Java version from the first line of the output. For example, the output openjdk version "16.0.1" 2021-04-20 indicates that the current Java version is Java 16. If Java is not installed in your environment or the version is earlier than Java 8, go to Java to download and install it.

Install SDK

To use the OCR Java SDK in a Maven project, add the corresponding dependency to the <dependencies> section in your pom.xml file. The following example is for version 3.1.2:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>ocr_api20210707</artifactId>
  <version>3.1.2</version>
</dependency>

Step 2: Call the OCR API

Run the following code to call the OCR API:

import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponse;
import com.aliyun.tea.*;
public class Sample {
    public static com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Ensure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Ensure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // The public endpoint is ocr-api.cn-hangzhou.aliyuncs.com. If you want to use a VPC endpoint, ensure your ECS instance is in the China (Hangzhou) region. The VPC endpoint is ocr-api-vpc.cn-hangzhou.aliyuncs.com.
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }
    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.ocr_api20210707.Client client = Sample.createClient();
        com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest recognizeAllTextRequest = new com.aliyun.ocr_api20210707.models.RecognizeAllTextRequest()
                .setUrl("https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg")
                .setType("IdCard");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            RecognizeAllTextResponse resp = client.recognizeAllTextWithOptions(recognizeAllTextRequest, runtime);
            System.out.println(com.aliyun.teautil.Common.toJSONString(resp.body.data));
        } catch (TeaException error) {
            // This is for demonstration purposes only. Handle exceptions with care and do not ignore them in your production code.
            // Error message
            System.out.println(error.getMessage());
            // Diagnostic address
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // This is for demonstration purposes only. Handle exceptions with care and do not ignore them in your production code.
            // Error message
            System.out.println(error.getMessage());
            // Diagnostic address
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Click to view the run result

{
	"height": 307,
	"subImageCount": 1,
	"subImages": [{
		"angle": 0,
		"kvInfo": {
			"data": {
				"address": "Honghui Mingyuan, Quxi Road-South Xizang Road, Shanghai",
				"ethnicity": "Han",
				"sex": "Female",
				"name": "Fang Dadai",
				"idNumber": "371002200610020000",
				"birthDate": "2006-10-02"
			},
			"kvCount": 6,
			"kvDetails": {
				"address": {
					"keyName": "address",
					"keyConfidence": 100,
					"value": "Honghui Mingyuan, Quxi Road-South Xizang Road, Shanghai",
					"valueConfidence": 100,
					"valueAngle": 0
				},
				"ethnicity": {
					"keyName": "ethnicity",
					"keyConfidence": 100,
					"value": "Han",
					"valueConfidence": 100,
					"valueAngle": 0
				},
				"sex": {
					"keyName": "sex",
					"keyConfidence": 100,
					"value": "Female",
					"valueConfidence": 100,
					"valueAngle": 0
				},
				"name": {
					"keyName": "name",
					"keyConfidence": 100,
					"value": "Fang Dadai",
					"valueConfidence": 100,
					"valueAngle": 0
				},
				"idNumber": {
					"keyName": "idNumber",
					"keyConfidence": 100,
					"value": "371002200610020000",
					"valueConfidence": 100,
					"valueAngle": 0
				},
				"birthDate": {
					"keyName": "birthDate",
					"keyConfidence": 100,
					"value": "2006-10-02",
					"valueConfidence": 100,
					"valueAngle": 0
				}
			}
		},
		"qualityInfo": {
			"isCopy": false
		},
		"subImageId": 0,
		"type": "Front side of ID card"
	}],
	"width": 483
}

Python

Step 1: Configure the Python environment
Check Python environment

Run the following command in a terminal to check if Python is installed in your current environment:

# If the command fails, try replacing python with python3.
python -V

Python 3.0 or later is required. If Python is not installed or your version does not meet the requirement, see Python for installation instructions.

Configure virtual environment (optional)

If you have Python installed, you can create a virtual environment to install the OCR Python SDK. This helps avoid dependency conflicts with other projects.

  1. Create a virtual environment

    Run the following command to create a virtual environment named .venv:

    # If the command fails, you can replace python with python3.
    python -m venv .venv
  2. Activate the virtual environment

    On Windows, run the following command to activate the virtual environment:

    .venv\Scripts\activate

    On macOS or Linux, run the following command to activate the virtual environment:

    source .venv/bin/activate
Install SDK

Run the following command to install the Python SDK:

pip install alibabacloud_ocr_api20210707==3.1.2

Step 2: Call the OCR API

You can create a new Python file, name it hello_ocr.py, copy the following code into hello_ocr.py, and save it.

# -*- coding: utf-8 -*-
import os
import sys
from typing import List
from alibabacloud_ocr_api20210707.client import Client as ocr_api20210707Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ocr_api20210707 import models as ocr_api_20210707_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
class Sample:
    def __init__(self):
        pass
    @staticmethod
    def create_client() -> ocr_api20210707Client:
        config = open_api_models.Config(
            # Ensure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Ensure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # The public endpoint is ocr-api.cn-hangzhou.aliyuncs.com. If you want to use a VPC endpoint, ensure your ECS instance is in the China (Hangzhou) region. The VPC endpoint is ocr-api-vpc.cn-hangzhou.aliyuncs.com.
        config.endpoint = f'ocr-api.cn-hangzhou.aliyuncs.com'
        return ocr_api20210707Client(config)
    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        recognize_all_text_request = ocr_api_20210707_models.RecognizeAllTextRequest(
            url='https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg',
            type='IdCard'
        )
        runtime = util_models.RuntimeOptions()
        try:
            resp = client.recognize_all_text_with_options(recognize_all_text_request, runtime)
            print(resp.body.data)
        except Exception as error:
            # This is for demonstration purposes only. Handle exceptions with care and do not ignore them in your production code.
            # Error message
            print(error.message)
            # Diagnostic address
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        recognize_all_text_request = ocr_api_20210707_models.RecognizeAllTextRequest(
            url='https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg',
            type='IdCard'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # When you run the copied code, you need to print the return value of the API.
            await client.recognize_all_text_with_options_async(recognize_all_text_request, runtime)
        except Exception as error:
            # This is for demonstration purposes only. Handle exceptions with care and do not ignore them in your production code.
            # Error message
            print(error.message)
            # Diagnostic address
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Click to view the run result

{
	'Height': 307,
	'SubImageCount': 1,
	'SubImages': [{
		'Angle': 0,
		'FigureInfo': {},
		'KvInfo': {
			'Data': {
				'address': 'Honghui Mingyuan, Quxi Road-South Xizang Road, Shanghai',
				'ethnicity': 'Han',
				'sex': 'Female',
				'name': 'Fang Dadai',
				'idNumber': '371002200610020000',
				'birthDate': '2006-10-02'
			},
			'KvCount': 6,
			'KvDetails': {
				'address': {
					'KeyName': 'address',
					'KeyConfidence': 100,
					'Value': 'Honghui Mingyuan, Quxi Road-South Xizang Road, Shanghai',
					'ValueConfidence': 100,
					'ValuePoints': [],
					'ValueAngle': 0
				},
				'ethnicity': {
					'KeyName': 'ethnicity',
					'KeyConfidence': 100,
					'Value': 'Han',
					'ValueConfidence': 100,
					'ValuePoints': [],
					'ValueAngle': 0
				},
				'sex': {
					'KeyName': 'sex',
					'KeyConfidence': 100,
					'Value': 'Female',
					'ValueConfidence': 100,
					'ValuePoints': [],
					'ValueAngle': 0
				},
				'name': {
					'KeyName': 'name',
					'KeyConfidence': 100,
					'Value': 'Fang Dadai',
					'ValueConfidence': 100,
					'ValuePoints': [],
					'ValueAngle': 0
				},
				'idNumber': {
					'KeyName': 'idNumber',
					'KeyConfidence': 100,
					'Value': '371002200610020000',
					'ValueConfidence': 100,
					'ValuePoints': [],
					'ValueAngle': 0
				},
				'birthDate': {
					'KeyName': 'birthDate',
					'KeyConfidence': 100,
					'Value': '2006-10-02',
					'ValueConfidence': 100,
					'ValuePoints': [],
					'ValueAngle': 0
				}
			}
		},
		'QualityInfo': {
			'IsCopy': False
		},
		'SubImageId': 0,
		'SubImagePoints': [],
		'Type': 'Front side of ID card'
	}],
	'Width': 483
}

Go

Step 1: Configure the Go environment
Check Go environment

Run the following command in a terminal to check if Go is installed in your current environment:

go version

Go 1.10 or a later version is required. You can check the first line of the output to confirm your Go version. For example, an output of go version go1.22.2 indicates that your Go version is 1.22.2. If Go is not installed in your environment or if the version is earlier than 1.10, download it from Go.

Install SDK

Run the following command to install the Go SDK dependency:

go get github.com/alibabacloud-go/ocr-api-20210707/v3

Step 2: Call the OCR API

You can create a new Go file named hello_ocr.go, copy the following code into hello_ocr.go, and save it.

package main
import (
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ocr_api20210707 "github.com/alibabacloud-go/ocr-api-20210707/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"os"
	"strings"
)
func CreateClient() (_result *ocr_api20210707.Client, _err error) {
	config := &openapi.Config{
		// Ensure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
		AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		// Ensure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// The public endpoint is ocr-api.cn-hangzhou.aliyuncs.com. If you want to use a VPC endpoint, ensure your ECS instance is in the China (Hangzhou) region. The VPC endpoint is ocr-api-vpc.cn-hangzhou.aliyuncs.com.
	config.Endpoint = tea.String("ocr-api.cn-hangzhou.aliyuncs.com")
	_result = &ocr_api20210707.Client{}
	_result, _err = ocr_api20210707.NewClient(config)
	return _result, _err
}
func _main(args []*string) (_err error) {
	client, _err := CreateClient()
	if _err != nil {
		return _err
	}
	recognizeAllTextRequest := &ocr_api20210707.RecognizeAllTextRequest{
		Url:  tea.String("https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg"),
		Type: tea.String("IdCard"),
	}
	runtime := &util.RuntimeOptions{}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		resp, _err := client.RecognizeAllTextWithOptions(recognizeAllTextRequest, runtime)
		if _err != nil {
			return _err
		}
		fmt.Println(resp.Body.Data)
		return nil
	}()
	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// This is for demonstration purposes only. Handle exceptions with care and do not ignore them in your production code.
		// Error message
		fmt.Println(tea.StringValue(error.Message))
		// Diagnostic address
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
		d.Decode(&data)
		if m, ok := data.(map[string]interface{}); ok {
			recommend, _ := m["Recommend"]
			fmt.Println(recommend)
		}
		_, _err = util.AssertAsString(error.Message)
		if _err != nil {
			return _err
		}
	}
	return _err
}
func main() {
	err := _main(tea.StringSlice(os.Args[1:]))
	if err != nil {
		panic(err)
	}
}

Click to view the run result

{
   "Height": 307,
   "SubImageCount": 1,
   "SubImages": [
      {
         "Angle": 0,
         "KvInfo": {
            "Data": {
               "address": "Honghui Mingyuan, Quxi Road-South Xizang Road, Shanghai",
               "birthDate": "2006-10-02",
               "ethnicity": "Han",
               "idNumber": "371002200610020000",
               "name": "Fang Dadai",
               "sex": "Female"
            },
            "KvCount": 6,
            "KvDetails": {
               "address": {
                  "KeyName": "address",
                  "KeyConfidence": 100,
                  "Value": "Honghui Mingyuan, Quxi Road-South Xizang Road, Shanghai",
                  "ValueConfidence": 100,
                  "ValueAngle": 0
               },
               "birthDate": {
                  "KeyName": "birthDate",
                  "KeyConfidence": 100,
                  "Value": "2006-10-02",
                  "ValueConfidence": 100,
                  "ValueAngle": 0
               },
               "ethnicity": {
                  "KeyName": "ethnicity",
                  "KeyConfidence": 100,
                  "Value": "Han",
                  "ValueConfidence": 100,
                  "ValueAngle": 0
               },
               "idNumber": {
                  "KeyName": "idNumber",
                  "KeyConfidence": 100,
                  "Value": "371002200610020000",
                  "ValueConfidence": 100,
                  "ValueAngle": 0
               },
               "name": {
                  "KeyName": "name",
                  "KeyConfidence": 100,
                  "Value": "Fang Dadai",
                  "ValueConfidence": 100,
                  "ValueAngle": 0
               },
               "sex": {
                  "KeyName": "sex",
                  "KeyConfidence": 100,
                  "Value": "Female",
                  "ValueConfidence": 100,
                  "ValueAngle": 0
               }
            }
         },
         "QualityInfo": {
            "IsCopy": false
         },
         "SubImageId": 0,
         "Type": "Front side of ID card"
      }
   ],
   "Width": 483
}

Next steps

  • For long-term use of the OCR service, see the billing documentation to choose a suitable billing model.

  • To track your API call volume, go to the Data Monitoring module in the OCR console. You can filter by API and time range. The call volume and QPS statistics are displayed as time-series charts. Hover over a point in the chart to view the data for that specific date. Currently, statistics are available only at the account level and cannot be filtered by the source IP address.

  • See the API Overview for a summary of all service call information.

  • If you encounter any issues, see the FAQ for solutions. If the issue persists, you can join the DingTalk group (35208328) for further assistance and support.

OCR recognition types

Recognition type

Name

Unified OCR

  • General types: High-Definition General OCR, Basic General OCR, General Handwriting, E-commerce Image Text, General Multi-language, Table, QR Code, Barcode.

  • ID document types: ID Card, Bank Card, Social Security Card, Household Register, Birth Certificate, Chinese Passport, International Passport, Exit-Entry Permit for Travelling to and from Hong Kong and Macao, Mainland Travel Permit for Hong Kong and Macao Residents, Hong Kong ID Card, International ID Card, Real Estate Ownership Certificate.

  • Vehicle and logistics types: Vehicle License, Driver's License, License Plate, Vehicle Identification Number (VIN), Vehicle Qualification Certificate, Motorcycle Registration Certificate, Waybill.

  • Invoice and receipt types: VAT Invoice, Unified Invoice for Motor Vehicle Sales, Quota Invoice, VAT Roll Invoice, General Machine-printed Invoice, Non-tax Revenue Invoice, Unified Invoice for Used Car Sales, Taxi Invoice, Tax Payment Certificate, Bank Acceptance Bill, Passenger Transport Ticket, Train Ticket, Air Travel Itinerary, Hotel Bill, Shopping Receipt, E-commerce Order Page, Ride-hailing Itinerary, Payment Details Page, Toll Invoice.

  • Enterprise qualification types: Business License, Official Seal, Medical Device Business Permit, Medical Device Manufacturing Permit, Cosmetics Manufacturing Permit, International Business License, Trademark Registration Certificate, Food Business Permit, Food Production Permit, Class II Medical Device Business Filing Certificate, Bank Account Opening Permit.

  • Mixed receipt types: Mixed Invoices.

General Character Recognition

General OCR, High-Definition Full Text Recognition, General Handwriting, Table, E-commerce Image Text, Document Structuring.

ID Document Recognition

ID Card, International Passport, Household Register, Real Estate Ownership Certificate, Bank Card, Birth Certificate, Chinese Passport, Exit-Entry Permit for Travelling to and from Hong Kong and Macao, Mainland Travel Permit for Hong Kong and Macao Residents, Hong Kong ID Card, Social Security Card, International ID Card.

Enterprise Qualification Recognition

Business License, Bank Account Opening Permit, Trademark Registration Certificate, Food Business Permit, Food Production Permit, Medical Device Manufacturing Permit, Medical Device Business Permit, Class II Medical Device Business Filing Certificate, Cosmetics Manufacturing Permit, International Business License, Business License Verification.

Invoice and Receipt Recognition

Mixed Invoices, Ride-hailing Itinerary, VAT Invoice, Train Ticket, Quota Invoice, Air Travel Itinerary, Taxi Invoice, VAT Roll Invoice, Unified Invoice for Motor Vehicle Sales, Unified Invoice for Used Car Sales, General Machine-printed Invoice, Toll Invoice, Passenger Transport Ticket, Tax Payment Certificate, E-commerce Order Page, Payment Details Page, Non-tax Revenue Invoice, Hotel Bill, Shopping Receipt, Bank Acceptance Bill, Invoice Verification.

Vehicle and Logistics Document Recognition

License Plate, Vehicle License, Driver's License, Vehicle Identification Number (VIN), Waybill, Motorcycle Registration Certificate, Vehicle Qualification Certificate.

Education Scene Recognition

Printed Math Formulas, Questions, Test Paper Question Segmentation, Oral Calculation Grading, Full-page Test Paper, Fine-grained Structuring.

Minority Language Character Recognition

General Multi-language, English-specific, Japanese, Russian, Korean, Thai, Latin.

ID and Receipt Verification

Business License, Invoice.