騰訊雲:通用文字識別之英文識別(本地圖片)
下面的代碼是識別本地圖片的,在線url圖片的可以參考官網文檔,因爲官網對於本地圖片識別的案例代碼介紹很少,文檔寫得對於新手來說不是很友好,在自己搗鼓好久之後才弄好,所以寫個博客來記錄一下。
需要替換的地方已經在代碼中註明,有不清楚的地方可以評論,看到會回覆。
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models
import base64
try:
# 用你的ID和KEY替換掉SecretId、SecretKey
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "ocr.tencentcloudapi.com"
# 使用TC3-HMAC-SHA256加密方法,不使用可能會報錯
clientProfile = ClientProfile("TC3-HMAC-SHA256")
clientProfile.httpProfile = httpProfile
# 按就近的使用,所以我用的是ap-shanghai
client = ocr_client.OcrClient(cred, "ap-shanghai", clientProfile)
req = models.EnglishOCRRequest()
# 將本地文件轉換爲ImageBase64
with open("E:\\image\\7.jpg", 'rb') as f:
base64_data = base64.b64encode(f.read())
s = base64_data.decode()
params = '{"ImageBase64":"%s"}' % s
req.from_json_string(params)
resp = client.EnglishOCR(req)
resp = resp.to_json_string()
# 將官網文檔裏輸出字符串格式的轉換爲字典,如果不需要可以直接print(resp)
resp = eval(resp)
# 下面都是從字典中取出識別出的文本內容,不需要其他的參數內容
resp_list = resp['TextDetections']
for resp in resp_list:
result = resp['DetectedText']
print(result)
except TencentCloudSDKException as err:
print(err)
下面是識別好的內容格式,如果想要官網的那種json輸出格式,就直接在resp = resp.to_json_string()之後打印輸出resp就行,然後直接excet …,就OK了。