This topic describes how to get started with the Optical Character Recognition (OCR) service.
Workflow
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
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.
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
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.
In the upper-right corner of the console, hover over your account avatar and click AccessKey Management.
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.
Choose a programming language
Choose your preferred language to call the OCR API.
Java
Step 1: Configure the Java environment
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);
}
}
}Python
Step 1: Configure the Python environment
Configure virtual environment (optional)
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:])Go
Step 1: Configure the Go environment
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)
}
}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.