华为云API文字识别OCR的高效性—AI中名副其实的电子眼

云服务、API、SDK,调试,查看,我都行

阅读短文您可以学习到:人工智能AI自言语言的情感分析、文本分词、文本翻译

1 IntelliJ IDEA 之API插件介绍

API插件支持 VS Code IDE、IntelliJ IDEA等平台、以及华为云自研 CodeArts IDE,基于华为云服务提供的能力,帮助开发者更高效、便捷的搭建应用。API插件关联华为云服务下的 API Explorer、DevStar、CodeLabs、SDK 中心和 CLI 中心产品,致力于为开发者提供更稳定、快速、安全的编程体验。

在本插件中,我们提供了但不局限于如下的功能:

对接华为云API开放平台,支持用户检索API、查看API文档、调试API、以及提供SDK示例代码供用户学习如何使用API。

提供华为云SDK代码片段补全功能,SDK依赖包自动引入,加速用户集成华为云API。

对接华为云开发体验馆Codelabs,提供500+云服务代码示例,向导式教程帮助用户快速学习。

说明:

在IntelliJ IDEA等系列平台和VS Code IDE,华为云API插件的名称是Huawei Cloud API。而在CodeArts IDE,API插件是IDE原生内置的,名称是华为云API开发套件。

API插件在IntelliJ IDEA等系列平台和VS Code IDE的使用依赖底座插件,请提前安装底座插件。

2  API插件安装--IntelliJ IDEA

2.1 IntelliJ IDEA等平台

安装准备:下载并安装JDK1.8或更高版本。下载并安装IntelliJ IDEA 2020.2或更高版本。

须知:IntellIj平台同时支撑包括Goland、Pycharm等在内的IDE,若在其它相关IDE上开发,请下载配置好对应语言的编译器或者解释器。这里以IDEA为例介绍IntelliJ平台插件的安装流程,其他IntelliJ系列的IDE请参考IDEA。

开始安装:

您可以在直接在IDE插件市场或者直接在JetBrains插件市场下载离线包安装。

IDE安装

  1. 在IntelliJ IDEA顶部菜单栏中选择File > Settings,在Settings对话框的左侧导航栏中单击Plugins。
  2. Plugins区域单击Marketplace,在搜索栏中输入Huawei Cloud API。
  3. Search Results区域会出现Huawei Cloud API,单击Install,完成后重启IDE。

    华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第1张图片

离线包安装:

  1. 进入插件市场搜索Huawei Cloud API,进入插件详情页,在Versions页签下选择想要版本的API插件,点击Download下载离线的插件压缩包保存到本地。。
  2. 在IntelliJ IDEA顶部菜单栏中选择File > Settings,在Settings对话框的左侧导航栏中单击Plugins。
  3. 在Plugins区域单击 ,再单击Install Plugin from Disk...。
  4. 在Choose Plugin File对话框中选择离线安装包(不用解压),并按照IntelliJ IDEA安装页面的提示,完成后续安装步骤。

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第2张图片

说明:若当前您想要安装插件的IntelliJ IDE已经在桌面打开,则进入插件市场搜索Huawei Cloud API,进入插件详情页,在右上角会识别到本地已经打开的IDE,点击相应按钮,在弹出的IDE窗口中点击ok,则IDE后台会开始安装相应版本的API插件。

安装验证:在IntelliJ系列平台上安装插件成功后在左侧的导航栏中可以看到Huawei Cloud Toolkit图标,点击后面板会出现Huawei Cloud API的字样,则说明安装成功。

2.2      API列表

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第3张图片

左侧展示API列表,可以查询所有API,目前云服务206,APIs9213

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第4张图片

华为云提供了文字识别服务端SDK,您可以直接集成服务端SDK来调用文字识别服务的相关API,从而实现对文字识别服务的快速操作。

该示例展示了如何通过go版SDK实现文字识别。

前期准备:

已注册华为云,并完成 实名认证 。

已订阅文字识别服务。

已具备开发环境,支持go 1.14及其以上版本。

已获取华为云账号对应的Access Key(AK)和Secret Access Key(SK)。请在华为云控制台“我的凭证 > 访问密钥”页面上创建和查看您的AK/SK。具体请参见访问密钥 。https://support.huaweicloud.com/usermanual-ca/zh-cn_topic_0046606340.html

已获取文字识别服务对应区域的项目ID,请在华为云控制台“我的凭证 > API凭证”页面上查看项目ID。具体请参见 API凭证。API凭证_我的凭证_用户指南_华为云。

环境配置:

// 启用go module
export GO111MODULE=on
export GONOSUMDB=*
//若下载不了sdk,则需要设置源
export GOPROXY=https://repo.huaweicloud.com/repository/goproxy/,direct
安装SDK及代码依赖:
// 安装华为云Go库
go get -u github.com/huaweicloud/huaweicloud-sdk-go-v3
// 安装依赖
go get github.com/json-iterator/go
go get github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/[email protected]
go get github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/[email protected]
go get github.com/huaweicloud/huaweicloud-sdk-go-v3/core/[email protected]

3 AI文字识别服务文字识别示例

3.1 go版本

导入依赖模块

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"
)

初始化认证信息以及文字识别服务的客户端

ak := ""
sk := ""
regionName := ""
imageBase64 := ""
// 初始化认证信息
auth := basic.NewCredentialsBuilder().
    WithAk(ak).
    WithSk(sk).
    Build()
// 获取服务调用client
client := ocr.NewOcrClient(
    ocr.OcrClientBuilder().
        WithRegion(region.ValueOf(regionName)).
        WithCredential(auth).
        Build())

相关参数说明如下

ak:华为云账号Access Key。

sk:华为云账号Secret Access Key 。

service region: 服务所在区域名称,例如:

cn-north-1 北京一

cn-north-4 北京四

CN_EAST_3 上海一

CN_SOUTH_1 华南广州

6.SDK demo代码解析

通用文字识别

request := &model.RecognizeGeneralTextRequest{}
quickModeGeneralTextRequestBody := true
detectDirectionGeneralTextRequestBody := true
imageGeneralTextRequestBody := imageBase64
request.Body = &model.GeneralTextRequestBody{
    QuickMode:       &quickModeGeneralTextRequestBody,
    DetectDirection: &detectDirectionGeneralTextRequestBody,
    Image:           &imageGeneralTextRequestBody,
}
response, err := client.RecognizeGeneralText(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

通用表格识别:

request := &model.RecognizeGeneralTableRequest{}
returnExcelGeneralTableRequestBody := true
returnConfidenceGeneralTableRequestBody := true
returnTextLocationGeneralTableRequestBody := true
imageGeneralTableRequestBody := imageBase64
request.Body = &model.GeneralTableRequestBody{
    ReturnExcel:        &returnExcelGeneralTableRequestBody,
    ReturnConfidence:   &returnConfidenceGeneralTableRequestBody,
    ReturnTextLocation: &returnTextLocationGeneralTableRequestBody,
    Image:              &imageGeneralTableRequestBody,
}
response, err := client.RecognizeGeneralTable(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

身份证识别

request := &model.RecognizeIdCardRequest{}
returnVerificationIdCardRequestBody := true
sideIdCardRequestBody := "front"
imageIdCardRequestBody := imageBase64
request.Body = &model.IdCardRequestBody{
    ReturnVerification: &returnVerificationIdCardRequestBody,
    Side:               &sideIdCardRequestBody,
    Image:              &imageIdCardRequestBody,
}
response, err := client.RecognizeIdCard(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

银行卡识别

request := &model.RecognizeBankcardRequest{}
imageBankcardRequestBody := imageBase64
request.Body = &model.BankcardRequestBody{
    Image: &imageBankcardRequestBody,
}
response, err := client.RecognizeBankcard(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

智能分类识别
request := &model.RecognizeAutoClassificationRequest{}
imageAutoClassificationRequestBody := imageBase64
request.Body = &model.AutoClassificationRequestBody{
    Image: &imageAutoClassificationRequestBody,
}
response, err := client.RecognizeAutoClassification(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

增值税发票识别

request := &model.RecognizeVatInvoiceRequest{}
advancedModeVatInvoiceRequestBody := true
imageVatInvoiceRequestBody := imageBase64
request.Body = &model.VatInvoiceRequestBody{
    AdvancedMode: &advancedModeVatInvoiceRequestBody,
    Image:        &imageVatInvoiceRequestBody,
}
response, err := client.RecognizeVatInvoice(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

定额发票识别

request := &model.RecognizeQuotaInvoiceRequest{}
imageQuotaInvoiceRequestBody := imageBase64
request.Body = &model.QuotaInvoiceRequestBody{
    Image: &imageQuotaInvoiceRequestBody,
}
response, err := client.RecognizeQuotaInvoice(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

手写文字识别

request := &model.RecognizeHandwritingRequest{}
detectDirectionHandwritingRequestBody := true
charSetHandwritingRequestBody := "digit"
quickModeHandwritingRequestBody := true
imageHandwritingRequestBody := imageBase64
request.Body = &model.HandwritingRequestBody{
    DetectDirection: &detectDirectionHandwritingRequestBody,
    CharSet:         &charSetHandwritingRequestBody,
    QuickMode:       &quickModeHandwritingRequestBody,
    Image:           &imageHandwritingRequestBody,
}
response, err := client.RecognizeHandwriting(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

行驶证识别

request := &model.RecognizeVehicleLicenseRequest{}
returnIssuingAuthorityVehicleLicenseRequestBody := true
sideVehicleLicenseRequestBody := "front"
imageVehicleLicenseRequestBody := imageBase64
request.Body = &model.VehicleLicenseRequestBody{
    ReturnIssuingAuthority: &returnIssuingAuthorityVehicleLicenseRequestBody,
    Side:                   &sideVehicleLicenseRequestBody,
    Image:                  &imageVehicleLicenseRequestBody,
}
response, err := client.RecognizeVehicleLicense(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

道路运输证识别

request := &model.RecognizeTransportationLicenseRequest{}
imageTransportationLicenseRequestBody := imageBase64
request.Body = &model.TransportationLicenseRequestBody{
    Image: &imageTransportationLicenseRequestBody,
}
response, err := client.RecognizeTransportationLicense(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

出租车发票识别

request := &model.RecognizeTaxiInvoiceRequest{}
imageTaxiInvoiceRequestBody := imageBase64
request.Body = &model.TaxiInvoiceRequestBody{
    Image: &imageTaxiInvoiceRequestBody,
}
response, err := client.RecognizeTaxiInvoice(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

车辆通行费发票识别

request := &model.RecognizeTollInvoiceRequest{}
imageTollInvoiceRequestBody := imageBase64
request.Body = &model.TollInvoiceRequestBody{
    Image: &imageTollInvoiceRequestBody,
}
response, err := client.RecognizeTollInvoice(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

机动车销售发票识别

request := &model.RecognizeMvsInvoiceRequest{}
imageMvsInvoiceRequestBody := imageBase64
request.Body = &model.MvsInvoiceRequestBody{
    Image: &imageMvsInvoiceRequestBody,
}
response, err := client.RecognizeMvsInvoice(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

车牌识别

request := &model.RecognizeLicensePlateRequest{}
imageLicensePlateRequestBody := imageBase64
request.Body = &model.LicensePlateRequestBody{
    Image: &imageLicensePlateRequestBody,
}
response, err := client.RecognizeLicensePlate(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

飞机行程单识别

request := &model.RecognizeFlightItineraryRequest{}
imageFlightItineraryRequestBody := imageBase64
request.Body = &model.FlightItineraryRequestBody{
    Image: &imageFlightItineraryRequestBody,
}
response, err := client.RecognizeFlightItinerary(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

营业执照识别

request := &model.RecognizeBusinessLicenseRequest{}
imageBusinessLicenseRequestBody := imageBase64
request.Body = &model.BusinessLicenseRequestBody{
    Image: &imageBusinessLicenseRequestBody,
}
response, err := client.RecognizeBusinessLicense(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

网络图片识别

request := &model.RecognizeWebImageRequest{}
var listExtractTypebody = []string{
    "contact_info",
    "image_size",
}
detectDirectionWebImageRequestBody := true
imageWebImageRequestBody := imageBase64
request.Body = &model.WebImageRequestBody{
    ExtractType:     &listExtractTypebody,
    DetectDirection: &detectDirectionWebImageRequestBody,
    Image:           &imageWebImageRequestBody,
}
response, err := client.RecognizeWebImage(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

驾驶证识别

request := &model.RecognizeDriverLicenseRequest{}
returnIssuingAuthorityDriverLicenseRequestBody := true
sideDriverLicenseRequestBody := "front"
imageDriverLicenseRequestBody := imageBase64
request.Body = &model.DriverLicenseRequestBody{
    ReturnIssuingAuthority: &returnIssuingAuthorityDriverLicenseRequestBody,
    Side:                   &sideDriverLicenseRequestBody,
    Image:                  &imageDriverLicenseRequestBody,
}
response, err := client.RecognizeDriverLicense(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

名片识别

request := &model.RecognizeBusinessCardRequest{}
returnAdjustedImageBusinessCardRequestBody := true
detectDirectionBusinessCardRequestBody := true
imageBusinessCardRequestBody := imageBase64
request.Body = &model.BusinessCardRequestBody{
    ReturnAdjustedImage: &returnAdjustedImageBusinessCardRequestBody,
    DetectDirection:     &detectDirectionBusinessCardRequestBody,
    Image:               &imageBusinessCardRequestBody,
}
response, err := client.RecognizeBusinessCard(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

火车票识别

request := &model.RecognizeTrainTicketRequest{}
imageTrainTicketRequestBody := imageBase64
request.Body = &model.TrainTicketRequestBody{
    Image: &imageTrainTicketRequestBody,
}
response, err := client.RecognizeTrainTicket(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

VIN码识别

request := &model.RecognizeVinRequest{}
imageVinRequestBody := imageBase64
request.Body = &model.VinRequestBody{
    Image: &imageVinRequestBody,
}
response, err := client.RecognizeVin(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

护照识别

request := &model.RecognizePassportRequest{}
imagePassportRequestBody := imageBase64
request.Body = &model.PassportRequestBody{
    Image: &imagePassportRequestBody,
}
response, err := client.RecognizePassport(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

保险单卡识别

request := &model.RecognizeInsurancePolicyRequest{}
detectDirectionInsurancePolicyRequestBody := true
imageInsurancePolicyRequestBody := imageBase64
request.Body = &model.InsurancePolicyRequestBody{
    DetectDirection: &detectDirectionInsurancePolicyRequestBody,
    Image:           &imageInsurancePolicyRequestBody,
}
response, err := client.RecognizeInsurancePolicy(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

道路运输从业资格证识别

request := &model.RecognizeQualificationCertificateRequest{}
imageQualificationCertificateRequestBody := imageBase64
request.Body = &model.QualificationCertificateRequestBody{
    Image: &imageQualificationCertificateRequestBody,
}
response, err := client.RecognizeQualificationCertificate(request)
if err == nil {
    fmt.Printf("%+v\n", response)
} else {
    fmt.Println(err)
}

3.2      python版本

开始使用

导入依赖模块

from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkocr.v1.region.ocr_region import OcrRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkocr.v1 import *

初始化认证信息

def get_credential():
    return BasicCredentials(ak, sk)

相关参数说明如下所示:

ak:华为云账号Access Key。

sk:华为云账号Secret Access Key 。

初始化文字识别服务的客户端

def get_client():
    return OcrClient.new_builder(OcrClient)
        .with_credentials(credentials)
        .with_region(OcrRegion.CN_NORTH_4)
        .build()

相关参数说明如下所示:

service region: 服务所在区域,例如:

CN_NORTH_1 北京一

CN_NORTH_4 北京四

CN_EAST_3 上海一

CN_SOUTH_1 华南广州

SDK demo代码解析

通用文字识别

def recognize_general_text_request():
    try:
        request = RecognizeGeneralTextRequest()
        request.body = GeneralTextRequestBody(
            image=image_base64
        )
        response = client.recognize_general_text(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

通用表格识别

def recognize_general_table_request():
    try:
        request = RecognizeGeneralTableRequest()
        request.body = GeneralTableRequestBody(
            image=image_base64
        )
        response = client.recognize_general_table(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

身份证识别

def recognize_id_card_request():
    try:
        request = RecognizeIdCardRequest()
        request.body = IdCardRequestBody(
            image=image_base64
        )
        response = client.recognize_id_card(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

银行卡识别

def recognize_bankcard_request():
    try:
        request = RecognizeBankcardRequest()
        request.body = BankcardRequestBody(
            image=image_base64
        )
        response = client.recognize_bankcard(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

智能分类识别

def recognize_auto_classification_request():
    try:
        request = RecognizeAutoClassificationRequest()
        request.body = AutoClassificationRequestBody(
            image=image_base64
        )
        response = client.recognize_auto_classification(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

增值税发票识别

def recognize_vat_invoice_request():
    try:
        request = RecognizeVatInvoiceRequest()
        request.body = VatInvoiceRequestBody(
            image=image_base64
        )
        response = client.recognize_vat_invoice(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

定额发票识别

def recognize_quota_invoice_request():
    try:
        request = RecognizeQuotaInvoiceRequest()
        request.body = QuotaInvoiceRequestBody(
            image=image_base64
        )
        response = client.recognize_quota_invoice(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

手写文字识别

def recognize_handwriting_request():
    try:
        request = RecognizeHandwritingRequest
        request.body = HandwritingRequestBody(
            image=image_base64
        )
        response = client.recognize_handwriting(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

行驶证识别

def recognize_vehicle_license_request():
    try:
        request = RecognizeIdCardRequest()
        request.body = VehicleLicenseRequestBody(
            image=image_base64
        )
        response = client.recognize_vehicle_license(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

道路运输证识别

def recognize_transportation_license_request():
    try:
        request = RecognizeTransportationLicenseRequest()
        request.body = TransportationLicenseRequestBody(
            image=image_base64
        )
        response = client.recognize_transportation_license(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

出租车发票识别

def recognize_taxi_invoice_request():
    try:
        request = RecognizeTaxiInvoiceRequest()
        request.body = TaxiInvoiceRequestBody(
            image=image_base64
        )
        response = client.recognize_taxi_invoice(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

车辆通行费发票识别

def recognize_toll_invoice_request():
    try:
        request = RecognizeTollInvoiceRequest()
        request.body = TollInvoiceRequestBody(
            image=image_base64
        )
        response = client.recognize_toll_invoice(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

机动车销售发票识别

def recognize_mvs_invoice_request():
    try:
        request = RecognizeMvsInvoiceRequest()
        request.body = MvsInvoiceRequestBody(
            image=image_base64
        )
        response = client.recognize_mvs_invoice(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

车牌识别

def recognize_license_plate_request():
    try:
        request = RecognizeLicensePlateRequest()
        request.body = LicensePlateRequestBody(
            image=image_base64
        )
        response = client.recognize_license_plate(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

飞机行程单识别

def recognize_flight_itinerary_request():
    try:
        request = RecognizeFlightItineraryRequest()
        request.body = FlightItineraryRequestBody(
            image=image_base64
        )
        response = client.recognize_flight_itinerary(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

营业执照识别

def recognize_business_license_request():
    try:
        request = RecognizeBusinessLicenseRequest()
        request.body = BusinessLicenseRequestBody(
            image=image_base64
        )
        response = client.recognize_business_license(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

网络图片识别

def recognize_web_image_request():
    try:
        request = RecognizeWebImageRequest()
        request.body = WebImageRequestBody(
            image=image_base64
        )
        response = client.recognize_web_image(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

驾驶证识别

def recognize_driver_license_request():
    try:
        request = RecognizeDriverLicenseRequest()
        request.body = DriverLicenseRequestBody(
            image=image_base64
        )
        response = client.recognize_driver_license(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

名片识别

def recognize_business_card_request():
    try:
        request = RecognizeBusinessCardRequest()
        request.body = BusinessCardRequestBody(
            image=image_base64
        )
        response = client.recognize_business_card(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

火车票识别

def recognize_train_ticket_request():
    try:
        request = RecognizeTrainTicketRequest()
        request.body = TrainTicketRequestBody(
            image=image_base64
        )
        response = client.recognize_train_ticket(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

VIN码识别

def recognize_vin_request():
    try:
        request = RecognizeVinRequest()
        request.body = VinRequestBody(
            image=image_base64
        )
        response = client.recognize_vin(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

护照识别

def recognize_passport_request():
    try:
        request = RecognizePassportRequest()
        request.body = PassportRequestBody(
            image=image_base64
        )
        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)

保险单识别

def recognize_insurance_policy_request():
    try:
        request = RecognizeInsurancePolicyRequest()
        request.body = InsurancePolicyRequestBody(
            image=image_base64
        )
        response = client.recognize_insurance_policy(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

道路运输从业资格证识别

def recognize_transportation_qualification_certificate_request():
    try:
        request = RecognizeQualificationCertificateRequest()
        request.body = QualificationCertificateRequestBody(
            image=image_base64
        )
        response = client.recognize_transportation_qualification_certificate(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

3.3      java版本

开始使用

导入依赖模块

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 static ICredential getCredential(String ak, String sk) {
    return new BasicCredentials().withAk(ak).withSk(sk);
}

相关参数说明如下所示:

ak:华为云账号Access Key。

sk:华为云账号Secret Access Key 。

初始化文字识别服务的客户端

public static OcrClient getClient(Region region, ICredential auth) {
    return OcrClient.newBuilder().withCredential(auth).withRegion(region).build();
}

相关参数说明如下所示:

service region: 服务所在区域,例如:

CN_NORTH_1 北京一

CN_NORTH_4 北京四

CN_EAST_3 上海一

CN_SOUTH_1 华南广州

SDK demo代码解析

通用文字识别

private static void generalText(OcrClient ocrClient, String image) {
    RecognizeGeneralTextRequest recognizeGeneralTextRequest = new RecognizeGeneralTextRequest();
    GeneralTextRequestBody requestBody = new GeneralTextRequestBody();
    requestBody.setImage(image);
    recognizeGeneralTextRequest.setBody(requestBody);
    try {
        RecognizeGeneralTextResponse textResponse = ocrClient.recognizeGeneralText(recognizeGeneralTextRequest);
        System.out.println(textResponse.getResult());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

通用表格识别

private static void generalTable(OcrClient ocrClient, String image) {
    RecognizeGeneralTableRequest request = new RecognizeGeneralTableRequest();
    GeneralTableRequestBody requestBody = new GeneralTableRequestBody();
    requestBody.withImage(image);
    request.withBody(requestBody);
    try {
        RecognizeGeneralTableResponse response = ocrClient.recognizeGeneralTable(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

身份证识别

private static void idCard(OcrClient ocrClient, String image) {
    RecognizeIdCardRequest request = new RecognizeIdCardRequest();
    IdCardRequestBody body = new IdCardRequestBody();
    body.withReturnVerification(true);
    body.withSide("front");
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeIdCardResponse response = ocrClient.recognizeIdCard(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

银行卡识别

private static void bankcard(OcrClient ocrClient, String image) {
    RecognizeBankcardRequest recognizeBankcardRequest = new RecognizeBankcardRequest();
    BankcardRequestBody bankcardRequestBody = new BankcardRequestBody();
    bankcardRequestBody.setImage(image);
    recognizeBankcardRequest.setBody(bankcardRequestBody);
    try {
        RecognizeBankcardResponse response = ocrClient.recognizeBankcard(recognizeBankcardRequest);
        System.out.println(response);
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

智能分类识别

private static void autoClassification(OcrClient ocrClient, String image) {
    RecognizeAutoClassificationRequest request = new RecognizeAutoClassificationRequest();
    AutoClassificationRequestBody requestBody = new AutoClassificationRequestBody();
    requestBody.withImage(image);
    request.setBody(requestBody);
    try {
        RecognizeAutoClassificationResponse response = ocrClient.recognizeAutoClassification(request);
        System.out.println(response);
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

增值税发票识别

private static void vatInvoice(OcrClient ocrClient, String image) {
    RecognizeVatInvoiceRequest request = new RecognizeVatInvoiceRequest();
    VatInvoiceRequestBody body = new VatInvoiceRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeVatInvoiceResponse response = ocrClient.recognizeVatInvoice(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

定额发票识别

private static void quotaInvoice(OcrClient ocrClient, String image) {
    RecognizeQuotaInvoiceRequest request = new RecognizeQuotaInvoiceRequest();
    QuotaInvoiceRequestBody body = new QuotaInvoiceRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeQuotaInvoiceResponse response = ocrClient.recognizeQuotaInvoice(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

手写文字识别

private static void handwriting(OcrClient ocrClient, String image) {
    RecognizeHandwritingRequest request = new RecognizeHandwritingRequest();
    HandwritingRequestBody body = new HandwritingRequestBody();
    body.withDetectDirection(true);
    body.withQuickMode(true);
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeHandwritingResponse response = ocrClient.recognizeHandwriting(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

行驶证识别

private static void vehicleLicense(OcrClient ocrClient, String image) {
    RecognizeVehicleLicenseRequest request = new RecognizeVehicleLicenseRequest();
    VehicleLicenseRequestBody body = new VehicleLicenseRequestBody();
    body.withReturnIssuingAuthority(true);
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeVehicleLicenseResponse response = ocrClient.recognizeVehicleLicense(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

道路运输证识别

private static void transportationLicense(OcrClient ocrClient, String image) {
    RecognizeTransportationLicenseRequest request = new RecognizeTransportationLicenseRequest();
    TransportationLicenseRequestBody body = new TransportationLicenseRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeTransportationLicenseResponse response = ocrClient.recognizeTransportationLicense(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

出租车发票识别

private static void taxiInvoice(OcrClient ocrClient, String image) {
    RecognizeTaxiInvoiceRequest request = new RecognizeTaxiInvoiceRequest();
    TaxiInvoiceRequestBody body = new TaxiInvoiceRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeTaxiInvoiceResponse response = ocrClient.recognizeTaxiInvoice(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

车辆通行费发票识别

private static void tollInvoice(OcrClient ocrClient, String image) {
    RecognizeTollInvoiceRequest request = new RecognizeTollInvoiceRequest();
    TollInvoiceRequestBody body = new TollInvoiceRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeTollInvoiceResponse response = ocrClient.recognizeTollInvoice(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

机动车销售发票识别

private static void mvsInvoice(OcrClient ocrClient, String image) {
    RecognizeMvsInvoiceRequest request = new RecognizeMvsInvoiceRequest();
    MvsInvoiceRequestBody body = new MvsInvoiceRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeMvsInvoiceResponse response = ocrClient.recognizeMvsInvoice(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

车牌识别

private static void licensePlate(OcrClient ocrClient, String image) {
    RecognizeLicensePlateRequest request = new RecognizeLicensePlateRequest();
    LicensePlateRequestBody body = new LicensePlateRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeLicensePlateResponse response = ocrClient.recognizeLicensePlate(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

飞机行程单识别

private static void flightItinerary(OcrClient ocrClient, String image) {
    RecognizeFlightItineraryRequest request = new RecognizeFlightItineraryRequest();
    FlightItineraryRequestBody body = new FlightItineraryRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeFlightItineraryResponse response = ocrClient.recognizeFlightItinerary(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

营业执照识别

private static void businessLicense(OcrClient ocrClient, String image) {
    RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
    BusinessLicenseRequestBody body = new BusinessLicenseRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeBusinessLicenseResponse response = ocrClient.recognizeBusinessLicense(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

网络图片识别

private static void webImage(OcrClient ocrClient, String image) {
    RecognizeWebImageRequest request = new RecognizeWebImageRequest();
    WebImageRequestBody body = new WebImageRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeWebImageResponse response = ocrClient.recognizeWebImage(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

驾驶证识别

private static void driverLicense(OcrClient ocrClient, String image) {
    RecognizeDriverLicenseRequest request = new RecognizeDriverLicenseRequest();
    DriverLicenseRequestBody body = new DriverLicenseRequestBody();
    body.withReturnIssuingAuthority(true);
    body.withSide("front");
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeDriverLicenseResponse response = ocrClient.recognizeDriverLicense(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

名片识别

private static void businessCard(OcrClient ocrClient, String image) {
    RecognizeBusinessCardRequest request = new RecognizeBusinessCardRequest();
    BusinessCardRequestBody body = new BusinessCardRequestBody();
    body.withDetectDirection(true);
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeBusinessCardResponse response = ocrClient.recognizeBusinessCard(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

火车票识别

private static void trainTicket(OcrClient ocrClient, String image) {
    RecognizeTrainTicketRequest request = new RecognizeTrainTicketRequest();
    TrainTicketRequestBody body = new TrainTicketRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeTrainTicketResponse response = ocrClient.recognizeTrainTicket(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

VIN码识别

private static void vin(OcrClient ocrClient, String image) {
    RecognizeVinRequest request = new RecognizeVinRequest();
    VinRequestBody body = new VinRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeVinResponse response = ocrClient.recognizeVin(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

护照识别

private static void passport(OcrClient ocrClient, String image) {
    RecognizePassportRequest request = new RecognizePassportRequest();
    PassportRequestBody body = new PassportRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizePassportResponse response = ocrClient.recognizePassport(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

保险单识别

private static void insurancePolicy(OcrClient ocrClient, String image) {
    RecognizeInsurancePolicyRequest request = new RecognizeInsurancePolicyRequest();
    InsurancePolicyRequestBody body = new InsurancePolicyRequestBody();
    body.withDetectDirection(true);
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeInsurancePolicyResponse response = ocrClient.recognizeInsurancePolicy(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
        LOGGER.error(String.valueOf(e.getHttpStatusCode()));
        LOGGER.error(e.getErrorCode());
        LOGGER.error(e.getErrorMsg());
    }
}

从业资格证识别

private static void qualificationCertificate(OcrClient ocrClient, String image) {
    RecognizeQualificationCertificateRequest request = new RecognizeQualificationCertificateRequest();
    QualificationCertificateRequestBody body = new QualificationCertificateRequestBody();
    body.withImage(image);
    request.withBody(body);
    try {
        RecognizeQualificationCertificateResponse response = ocrClient.recognizeQualificationCertificate(request);
        System.out.println(response.toString());
    } catch (ConnectionException | RequestTimeoutException e) {
        LOGGER.error(e.toString());
    } catch (ServiceResponseException e) {
       LOGGER.error(String.valueOf(e.getHttpStatusCode()));
       LOGGER.error(e.getErrorCode());
       LOGGER.error(e.getErrorMsg());
    }
}

4 体验馆

4.1  通用类

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第5张图片

4.2  票据类

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第6张图片

4.3  证件类

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第7张图片

4.4  行业类

华为云API文字识别OCR的高效性—AI中名副其实的电子眼_第8张图片

5  体验插件的魅力

华为云devkit已上线:Toolkit-华为云

你可能感兴趣的:(华为云,云计算,API,插件)