Updated on 2024-06-19 GMT+08:00

Passport

Function

This API detects and extracts text from the first page of images of passports and converts the text into a structured JSON format.

In the current version, all fields of a Chinese ordinary electronic passport issued in 2012 or later can be recognized. For passports issued by Hong Kong (China), Macao (China), and Taiwan (China), as well as non-Chinese passports, two lines of internationally standardized machine-readable codes on the bottom of each passport can be recognized, and 7 key fields can be extracted from the codes.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 passport

Constraints and Limitations

  • All fields on Chinese mainland passports can be recognized.
  • Passports that are issued by China, Hong Kong (China), Macao (China), Taiwan (China), and other countries and regions and that are with complete machine-readable codes 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.
  • The information page of the passport to be recognized must occupy more than 25% of the image. When scanning a passport, ensure that the entire page is displayed in the image.
  • A passport can be rotated to any angle.
  • The passport 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.

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 referring to Subscribing to an OCR Service. 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/passport

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.

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

image

No

String

Set either this parameter or url.

Base64-encoded 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.
  • The URL cannot contain Chinese characters. If Chinese characters exist, they must be encoded using UTF-8.

country_code

No

String

Code of the country where the passport is issued. The passport recognition service is determined based on the country code.

  • If this parameter is left blank, OCR automatically matches the recognition mode based on the passport type identified by the service.
  • If you set this parameter to GENERAL, the passport is recognized based on the machine-readable code.
  • If this parameter is set to CHN, all fields in the Chinese passport are recognized.

Response Parameters

The status code may vary depending on the recognition results. For example, 200 indicates that the API is successfully called, and 400 indicates that the API fails to be called. The following describes the status codes and corresponding response parameters.

Status code: 200

Table 4 Response body parameter

Parameter

Type

Description

result

PassportResult object

Recognition result

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

This parameter consists of the following three parts: 13 key fields, expressed in English; extra_info, expressed in local official language; and confidence of key fields. A higher confidence indicates a more accurate result.

Table 5 PassportResult

Parameter

Type

Description

passport_type

String

Passport type. The options are:

  • P: ordinary passport for private affairs
  • W: diplomatic passport
  • G: service passport
NOTE:

This field is returned only for Chinese mainland passports.

country_code

String

Country code

passport_number

String

Passport number

nationality

String

Nationality of the passport holder
NOTE:

This field is returned only for Chinese mainland passports.

surname

String

Family name

given_name

String

Given name

sex

String

Gender

date_of_birth

String

Date of birth, for example, 1990-12-12

date_of_expiry

String

Passport date of expiry, for example, 2020-07-08

date_of_issue

String

Date of issue, for example, 2010-07-09
NOTE:

This field is returned only for Chinese mainland passports.

place_of_birth

String

Place of birth
NOTE:

This field is returned only for Chinese mainland passports.

place_of_issue

String

Place of issue
NOTE:

This field is returned only for Chinese mainland passports.

issuing_authority

String

Issuing authority

The abbreviation of the issuing authority of each consulate is not unified. The abbreviation of Chinese issuing authority is P.R.China. For example, if the issuing authority is P.R.C, the recognition result is P.R.China.
NOTE:

This field is returned only for Chinese mainland passports.

confidence

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.

extra_info

Object

This parameter is left blank by default. For a Chinese passport, the extra_info value contains Chinese character-described fields on the passport, such as the name and place of birth.
NOTE:

This field is returned only for Chinese mainland passports.

Status code: 400

Table 6 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 when the API is successfully called.

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, Passport OCR is deployed in the CN-Hong Kong region. The endpoint is ocr.ap-southeast-1.myhuaweicloud.com or ocr.ap-southeast-1.myhuaweicloud.cn. The request URL is https://ocr.ap-southeast-1.myhuaweicloud.com/v2/{project_id}/ocr/passport. 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 Authentication.
  • Read the Base64 encoded string of a passport image for recognition.
    POST https://{endpoint}/v2/{project_id}/ocr/passport
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDTALBglghkgBZQMEAgEwgguVBgkqhkiG...
    Request Body:
    {
        "image":"/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAA...",
        "country_code": "GENERAL"
    }
  • Read the URL of a passport image for recognition.
    POST https://{endpoint}/v2/{project_id}/ocr/passport
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDTALBglghkgBZQMEAgEwgguVBgkqhkiG...
    Request Body:
    {
        "url":"https://BucketName.obs.xxxx.com/ObjectName",
        "country_code": "GENERAL"
    }

Example Response

Status code: 200

Chinese passport

{
    "result": {
        "passport_type": "P", 
        "country_code": "CHN", 
        "passport_number": "ED999XXXX", 
        "nationality": "CHINESE", 
        "surname": "ZHANG", 
        "given_name": "SAN", 
        "sex": "F", 
        "date_of_birth": "1990-12-12", 
        "date_of_expiry": "2020-07-08", 
        "date_of_issue": "2010-07-09", 
        "place_of_birth": "HUNAN", 
        "place_of_issue": "GUANGDONG", 
        "issuing_authority": "MPS Exit & Entry Administration", 
        "extra_info": {
            "local_language": {
                 "name": "Zhang San",
                "sex": "Female",
                "place_of_birth": "Hunan",
                "place_of_issue": "Guangdong",
                "issuing_authority": "xxx Entry and Exit Administration",
                "nationality": "China",
            }
        }, 
        "confidence": {
            "passport_type": 0.9987, 
            "country_code": 0.9897, 
            "passport_number": 0.9997, 
            "nationality": 0.9977, 
            "surname": 0.9729, 
            "given_name": 0.9729, 
            "sex": 0.9897, 
            "date_of_birth": 0.9998, 
            "date_of_expiry": 0.9995, 
            "date_of_issue": 0.9969, 
            "place_of_birth": 0.9937, 
            "place_of_issue": 0.9993, 
            "issuing_authority": 0.9985
        }
    }
}

Non-Chinese passport

{
    "result": {
        "country_code": "ETF", 
        "surname": "HUZHAO", 
        "given_name": "ZHAOMIN DESALEGN ", 
        "passport_number": "EP435XXXX", 
        "date_of_birth": "1985-09-18", 
        "sex": "M", 
        "date_of_expiry": "2022-01-15", 
        "machine_code": "P<ETFHUZHAO<< ZHAOMIN <DESALEGN<<<<<<<<<<<<<<<", 
        "machine_code2": "EP435XXXX7ETF8509185M2201155<<<<<<<<<<<<<<08", 
        "extra_info": {},
        "confidence": {
            "country_code": 0.9727, 
            "surname": 0.9727, 
            "given_name": 0.9727, 
            "passport_number": 0.9558, 
            "date_of_birth": 0.9558, 
            "sex": 0.9558, 
            "date_of_expiry": 0.9558
        }
    }
}

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.

  • Read the Base64 encoded string of a passport 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
    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 RecognizePassportSolution {
    
        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();
            RecognizePassportRequest request = new RecognizePassportRequest();
            PassportRequestBody body = new PassportRequestBody();
            body.withCountryCode("CHN");
            body.withImage("/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAAg...");
            request.withBody(body);
            try {
                RecognizePassportResponse response = client.recognizePassport(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());
            }
        }
    }
    
  • Read the URL of a passport 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
    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 RecognizePassportSolution {
    
        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();
            RecognizePassportRequest request = new RecognizePassportRequest();
            PassportRequestBody body = new PassportRequestBody();
            body.withCountryCode("CHN");
            body.withUrl("https://BucketName.obs.myhuaweicloud.com/ObjectName");
            request.withBody(body);
            try {
                RecognizePassportResponse response = client.recognizePassport(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());
            }
        }
    }
    
  • Read the Base64 encoded string of a passport 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
    # 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 = RecognizePassportRequest()
            request.body = PassportRequestBody(
                country_code="CHN",
                image="/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAAg..."
            )
            response = client.recognize_passport(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Read the URL of a passport 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
    # 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 = RecognizePassportRequest()
            request.body = PassportRequestBody(
                country_code="CHN",
                url="https://BucketName.obs.myhuaweicloud.com/ObjectName"
            )
            response = client.recognize_passport(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Read the Base64 encoded string of a passport 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
    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.RecognizePassportRequest{}
    	countryCodePassportRequestBody:= "CHN"
    	imagePassportRequestBody:= "/9j/4AAQSkZJRgABAgEASABIAAD/4RFZRXhpZgAATU0AKgAAAAg..."
    	request.Body = &model.PassportRequestBody{
    		CountryCode: &countryCodePassportRequestBody,
    		Image: &imagePassportRequestBody,
    	}
    	response, err := client.RecognizePassport(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • Read the URL of a passport 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
    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.RecognizePassportRequest{}
    	countryCodePassportRequestBody:= "CHN"
    	urlPassportRequestBody:= "https://BucketName.obs.myhuaweicloud.com/ObjectName"
    	request.Body = &model.PassportRequestBody{
    		CountryCode: &countryCodePassportRequestBody,
    		Url: &urlPassportRequestBody,
    	}
    	response, err := client.RecognizePassport(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.