Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
Software Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Updated on 2024-06-19 GMT+08:00

Thailand ID Card

Function

This API detects and extracts text from images of Thailand-issued national registration cards and converts the text into a structured JSON format. For details about the constraints on using this API, see Constraints and Limitations. For details about how to use this API, see Introduction to OCR.

Figure 1 Example Thailand ID card

Constraints and Limitations

  • Only ID cards issued by Thailand can be recognized.
  • Only images in PNG, JPG, JPEG, BMP, or TIFF format can be recognized.
  • No side of the image can be smaller than 15 or larger than 8,192 pixels.
  • An ID card to be recognized must occupy more than 25% of the image. When scanning an ID card, ensure that the entire ID card is displayed in the image.
  • An ID card can be rotated to any angle.
  • The ID card in the image can be moderately distorted, but the aspect ratio cannot be distorted by more than 10%.
  • Illuminated or dark images can be recognized, but the accuracy may be compromised.
  • Only the front or back of a single ID card can be identified each time.

Calling Method

For details, see Calling APIs.

Prerequisites

Before using this API, subscribe to the service and complete authentication. For details, see Subscribing to an OCR Service and Authentication.

Before you use the service for the first time, subscribe to the service by clicking Subscribe. You only need to subscribe to the service once. If you have not subscribed to the service yet, error "ModelArts.4204" will be displayed when you call this API. Before you call the API, log in to the OCR console and subscribe to the corresponding service. Ensure that you make the subscription to the service in the same region where you want to call this API.

URI

POST /v2/{project_id}/ocr/thailand-id-card

Table 1 URI parameters

Parameter

Mandatory

Description

endpoint

Yes

Endpoint, which is the request address for calling an API.

The endpoint varies depending on services in different regions. For more details, see Endpoints.

project_id

Yes

Project ID, which can be obtained by referring to Obtaining a Project ID.

Request Parameters

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

User token

Used to obtain the permission to call APIs. The token is the value of X-Subject-Token in the response header in Authentication.

Content-Type

Yes

String

MIME type of the request body. The value is application/json.

Enterprise-Project-Id

No

String

Enterprise project ID. OCR uses Enterprise Project Management Service (EPS) to split fees for resources used by different user groups and users.

To obtain the enterprise project ID, go to the Enterprise Project Management console, click the enterprise project name, and obtain the enterprise project ID on the enterprise project details page.

For details about how to create an enterprise project, see Optical Character Recognition User Guide.

NOTE:

After an enterprise project is created, parameter transfer involves the following scenarios:

  • If a correct enterprise project ID is carried and the OCR service can be used properly, the bills will be categorized under the corresponding enterprise project for that ID.
  • If an enterprise project ID that is in the correct format but does not actually exist is carried, and the OCR service can be used properly, the bills will display the corresponding non-existent enterprise project ID.
  • If no enterprise project ID or an enterprise project ID with incorrect format (such as special characters) is carried, and the OCR service can be used properly, the bills will be categorized under default.
Table 3 Request body parameters

Parameter

Mandatory

Type

Description

image

No

String

Set either this parameter or url.

Base64 encoded string of an image file. The image file has a size limit of 10 MB.

No side of the image can be smaller than 15 or larger than 8,192 pixels. Only images in JPEG, JPG, PNG, BMP, or TIFF format can be recognized.

An example is /9j/4AAQSkZJRgABAg.... If the image data contains an unnecessary prefix, the error "The image format is not supported" is reported.

url

No

String

Set either this parameter or image.

Image URL. Currently, the following URLs are supported:

  • Public HTTP/HTTPS URL
  • URL provided by OBS. You need to be authorized to use OBS data, including service authorization, temporary authorization, and anonymous public authorization. For details, see Configuring Access Permissions of OBS.
NOTE:
  • The API response time depends on the image download time. If the image download takes a long time, the API call will fail.
  • Ensure that the storage service where the image to be detected resides is stable and reliable. OBS is recommended for storing image data.

side

No

String

Front or back of the ID card. The options are:

  • front: front of an ID card
  • back: back of an ID card

If the value of this parameter is empty or not included, the system will automatically recognize whether the image is the front or back of an ID card. It is recommended to set this parameter for higher accuracy.

return_portrait_image

No

Boolean

Whether to return the Base64 encoded string of the portrait on the ID card image. The options are:

  • true: The Base64 encoded string of the portrait on the ID card will be returned.
  • false: The Base64 encoded string of the portrait on the ID card will not be returned.

If this parameter is not specified, false is used by default. In this case, the Base64 encoded string of the portrait on the ID card will not be returned.

return_portrait_location

No

Boolean

Whether to return the position coordinates of the portrait on the ID card image. The options are:

  • true: The location of the portrait on the ID card will be returned.
  • false: The location of the portrait on the ID card will not be returned.

return_idcard_type

No

Boolean

Whether to return the ID card type. The options are:

  • true: The ID card type will be returned, indicating that the ID card is the original ID card or copy of the original ID card.
  • false: The ID card type will not be returned.

return_text_location

No

Boolean

Location of a text block. The options are:

true: All text blocks will be returned.

false: Text blocks will not be returned.

If this parameter is not specified, the system does not return the location of any text blocks by default. If a non-Boolean value is entered, an error message will be displayed, indicating that the parameter is invalid.

Response Parameters

Status code: 200

Table 4 Response body parameter

Parameter

Type

Description

result

ThailandIdcardResult object

Recognition result

This parameter is not returned when the API fails to be called.

Table 5 ThailandIdcardResult

Parameter

Type

Description

type

String

ID card type. The value normal indicates a regular Thailand ID card, and the value pink indicates a foreigner's ID card.

name_en

String

English name

ref_number

String

Reference number

side

String

Front or back of an ID card. Value options are front and back.

id_number

String

ID number

name_th

String

Thai name

first_name_en

String

Name, in English

last_name_en

String

English surname

date_of_birth_th

String

Date of birth, in Thai

date_of_birth_en

String

Date of birth, in English

religion_th

String

Religion

address_th

String

Address

date_of_issue_th

String

Date of issue, in Thai

date_of_issue_en

String

Date of issue, in English

date_of_expiry_th

String

Date of expiry, in Thai

date_of_expiry_en

String

Date of expiry, in English

serial_number

String

Serial number

card_number

String

ID number on the back of the ID card

laser_number

String

Laser code

confidence

ThailandIdcardConfidence object

Confidence of a field. The value ranges from 0 to 1.

A higher confidence indicates a higher accuracy of the field identified. The confidence is calculated using algorithms and is not equal to the accuracy.

portrait_image

String

Base64 encoded string of the portrait. This parameter is returned only when return_portrait_image is set to true.

portrait_location

Array<Array<Integer>>

Location of the portrait on the original image. This parameter is returned only when return_portrait_location is set to true. The image is displayed in a list. The list contains the two-dimensional coordinates (x,y) of the four vertices in the portrait area. The origin of the coordinates is the upper left corner of the image. The X axis is horizontal, and the Y axis is vertical.

idcard_type

String

ID card type. This parameter is returned only when return_idcard_type is set to true. The options are:

  • normal: original ID card
  • copy: copy of the ID card

text_location

Object

Location of all fields identified on the original image, including the two-dimensional coordinates (x,y) of the four vertices in all text areas. The image coordinate system is used. The coordinate origin is the upper left corner of the image, the X axis is horizontal, and the Y axis is vertical.

Table 6 ThailandIdcardConfidence

Parameter

Type

Description

id_number

Float

Confidence of the ID number

name_th

Float

Confidence of the Thai name

name_en

Float

Confidence of the English name

ref_number

Float

Confidence of the reference number

first_name_en

Float

Confidence of the English given name

last_name_en

Float

Confidence of the English family name

date_of_birth_th

Float

Confidence of the birth date in Thai An example of the return value is 5 ก. พ. 2493.

date_of_birth_en

Float

Confidence of the birth date in English An example of the return value is 5 Feb. 1950.

religion_th

Float

Confidence of the religion

address_th

Float

Confidence of the address

date_of_issue_th

Float

Confidence of the issuance date in Thai

date_of_issue_en

Float

Confidence of the issuance date in English

date_of_expiry_th

Float

Confidence of the validity period in Thai

date_of_expiry_en

Float

Confidence of the validity period in English

serial_number

Float

Confidence of the serial number

card_number

Float

Confidence of the card number on the back of the ID card

laser_number

Float

Confidence of the laser code

Status code: 200

Table 7 Response body parameters

Parameter

Type

Description

error_code

String

Error code of a failed API call. For details, see Error Codes.

This parameter is not returned for a successful call.

error_msg

String

Error message when the API call fails

This parameter is not returned when the API is successfully called.

Example Request

  • endpoint is the request URL for calling an API. Endpoints vary depending on services and regions. For details, see Endpoints.

    For example, Thailand ID Card OCR is deployed in the AP-Bangkok region. The endpoint is ocr.ap-southeast-2.myhuaweicloud.com or ocr.ap-southeast-2.myhuaweicloud.cn. The request URL is https://ocr.ap-southeast-2.myhuaweicloud.com/v2/{project_id}/thailand-id-card. project_id is the project ID. For how to obtain the project ID, see Obtaining a Project ID.

  • For details about how to obtain a token, see Making an API Request.
  • Request example (Method 1: Use the image Base64 string.)
    POST  https://{endpoint}/v2/{project_id}/ocr/thailand-id-card
    
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDTALBglghkgBZQMEAgEwgguVBgkqhkiG...
    Request Body: 
    
    {
      "image" : "/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAA...",
      "side" : "front",
      "return_portrait_image" : true,
      "return_portrait_location" : true,
      "return_idcard_type" : true
    }
  • Request example (Method 2: Use the image URL.)
    POST  https://{endpoint}/v2/{project_id}/ocr/thailand-id-card
    
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDTALBglghkgBZQMEAgEwgguVBgkqhkiG...
    Request Body: 
    {
        "url":"https://BucketName.obs.xxxx.com/ObjectName"
    }
  • Sample code for a Python 3 request (For codes in other languages, refer to the following sample or use OCR SDK.)
    # encoding:utf-8
    
    import requests
    import base64
    
    url = "https://{endpoint}/v2/{project_id}/ocr/thailand-id-card"
    token = "Actual token value obtained by the user"
    headers = {'Content-Type': 'application/json', 'X-Auth-Token': token}
    
    imagepath = r'./data/thailand-id-card-demo.png' # Read a local image.
    with open(imagepath, "rb") as bin_data:
        image_data = bin_data.read()
    image_base64 = base64.b64encode(image_data).decode("utf-8")  # Use the Base64 encoded string of the image.
    payload = {"image": image_base64}
    response = requests.post(url, headers=headers, json=payload)
    print(response.text)

Example Response

Status code: 200

Example response for a successful request (the front)

{
  "result" : {
    "side" : "front",
    "id_number" : "X XXXX XXXXX XX X",
    "name_th" : "XXX",
    "first_name_en" : "XX",
    "last_name_en" : "XX",
    "date_of_birth_th" : "5 ก.พ. 2493",
    "date_of_birth_en" : "5 Feb. 1950",
    "religion_th" : "XX",
    "address_th" : "XXXXX",
    "date_of_issue_th" : "XX",
    "date_of_issue_en" : "4 Mar. 2011",
    "date_of_expiry_th" : "22 ก.พ. 2561",
    "date_of_expiry_en" : "22 Feb. 2018",
    "serial_number" : "XXXX-XX-XXXXX",
    "confidence" : {
      "id_number" : 0.9999,
      "name_th" : 0.9994,
      "first_name_en" : 0.998,
      "last_name_en" : 0.9997,
      "date_of_birth_th" : 0.9996,
      "date_of_birth_en" : 0.9997,
      "religion_th" : 0.686,
      "address_th" : 0.624,
      "date_of_issue_th" : 1,
      "date_of_issue_en" : 1,
      "date_of_expiry_th" : 0.9969,
      "date_of_expiry_en" : 0.61,
      "serial_number" : 0.9887
    },
    "portrait_image" : "/9j/4AA... ",
    "portrait_location" : [ [ 576, 237 ], [ 741, 237 ], [ 739, 430 ], [ 574, 431 ] ],
    "idcard_type" : "normal"
  }
}

Example response for a successful request (the back)

{
    "result": {
        "side": "back",
        "card_number": "XXXX-XXX-XX", 
        "laser_number": "XXXX-XXXXXXX-XX", 
        "confidence": {
            "id_number": 0.9999, 
            "laser_number": 0.9994
        }
    }
}

Status code: 400

Example response for a failed request

{
    "error_code": "AIS.0103", 
    "error_msg": "The image size does not meet the requirements." 
}

Example SDK Code

The example SDK code is as follows:

You are advised to update the SDKs to the latest versions before use to prevent the local outdated SDKs from being unable to use the latest OCR functions.

  • Transfer the Base64 encoded string of the Thailand ID card image for recognition.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
    import com.huaweicloud.sdk.ocr.v1.*;
    import com.huaweicloud.sdk.ocr.v1.model.*;
    
    
    public class RecognizeThailandIdcardSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withAk(ak)
                    .withSk(sk);
    
            OcrClient client = OcrClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(OcrRegion.valueOf("<YOUR REGION>"))
                    .build();
            RecognizeThailandIdcardRequest request = new RecognizeThailandIdcardRequest();
            ThailandIdcardRequestBody body = new ThailandIdcardRequestBody();
            body.withReturnIdcardType(true);
            body.withReturnPortraitLocation(true);
            body.withReturnPortraitImage(true);
            body.withSide("front");
            body.withImage("/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAA...");
            request.withBody(body);
            try {
                RecognizeThailandIdcardResponse response = client.recognizeThailandIdcard(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • Transfer the URL of the Thailand ID card image for recognition.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
    import com.huaweicloud.sdk.ocr.v1.*;
    import com.huaweicloud.sdk.ocr.v1.model.*;
    
    
    public class RecognizeThailandIdcardSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withAk(ak)
                    .withSk(sk);
    
            OcrClient client = OcrClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(OcrRegion.valueOf("<YOUR REGION>"))
                    .build();
            RecognizeThailandIdcardRequest request = new RecognizeThailandIdcardRequest();
            ThailandIdcardRequestBody body = new ThailandIdcardRequestBody();
            body.withReturnIdcardType(true);
            body.withReturnPortraitLocation(true);
            body.withReturnPortraitImage(true);
            body.withSide("front");
            body.withUrl("https://BucketName.obs.myhuaweicloud.com/ObjectName");
            request.withBody(body);
            try {
                RecognizeThailandIdcardResponse response = client.recognizeThailandIdcard(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • Transfer the Base64 encoded string of the Thailand ID card image for recognition.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkocr.v1.region.ocr_region import OcrRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkocr.v1 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.getenv("CLOUD_SDK_AK")
        sk = os.getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
    
        client = OcrClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(OcrRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = RecognizeThailandIdcardRequest()
            request.body = ThailandIdcardRequestBody(
                return_idcard_type=True,
                return_portrait_location=True,
                return_portrait_image=True,
                side="front",
                image="/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAA..."
            )
            response = client.recognize_thailand_idcard(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Transfer the URL of the Thailand ID card image for recognition.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkocr.v1.region.ocr_region import OcrRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkocr.v1 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.getenv("CLOUD_SDK_AK")
        sk = os.getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
    
        client = OcrClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(OcrRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = RecognizeThailandIdcardRequest()
            request.body = ThailandIdcardRequestBody(
                return_idcard_type=True,
                return_portrait_location=True,
                return_portrait_image=True,
                side="front",
                url="https://BucketName.obs.myhuaweicloud.com/ObjectName"
            )
            response = client.recognize_thailand_idcard(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Transfer the Base64 encoded string of the Thailand ID card image for recognition.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        ocr "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            Build()
    
        client := ocr.NewOcrClient(
            ocr.OcrClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.RecognizeThailandIdcardRequest{}
    	returnIdcardTypeThailandIdcardRequestBody:= true
    	returnPortraitLocationThailandIdcardRequestBody:= true
    	returnPortraitImageThailandIdcardRequestBody:= true
    	sideThailandIdcardRequestBody:= "front"
    	imageThailandIdcardRequestBody:= "/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAA..."
    	request.Body = &model.ThailandIdcardRequestBody{
    		ReturnIdcardType: &returnIdcardTypeThailandIdcardRequestBody,
    		ReturnPortraitLocation: &returnPortraitLocationThailandIdcardRequestBody,
    		ReturnPortraitImage: &returnPortraitImageThailandIdcardRequestBody,
    		Side: &sideThailandIdcardRequestBody,
    		Image: &imageThailandIdcardRequestBody,
    	}
    	response, err := client.RecognizeThailandIdcard(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • Transfer the URL of the Thailand ID card image for recognition.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        ocr "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ocr/v1/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            Build()
    
        client := ocr.NewOcrClient(
            ocr.OcrClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.RecognizeThailandIdcardRequest{}
    	returnIdcardTypeThailandIdcardRequestBody:= true
    	returnPortraitLocationThailandIdcardRequestBody:= true
    	returnPortraitImageThailandIdcardRequestBody:= true
    	sideThailandIdcardRequestBody:= "front"
    	urlThailandIdcardRequestBody:= "https://BucketName.obs.myhuaweicloud.com/ObjectName"
    	request.Body = &model.ThailandIdcardRequestBody{
    		ReturnIdcardType: &returnIdcardTypeThailandIdcardRequestBody,
    		ReturnPortraitLocation: &returnPortraitLocationThailandIdcardRequestBody,
    		ReturnPortraitImage: &returnPortraitImageThailandIdcardRequestBody,
    		Side: &sideThailandIdcardRequestBody,
    		Url: &urlThailandIdcardRequestBody,
    	}
    	response, err := client.RecognizeThailandIdcard(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    

For more SDK code examples in various programming languages, see the Sample Code tab on the right of the API Explorer page, which can automatically generate corresponding SDK code examples.

Status Codes

Status Code

Description

200

Example response for a successful request

400

Example response for a failed request

See Status Codes.

Error Codes

See Error Codes.