1.申請(qǐng)API key
騰訊云目前提供每個(gè)月1000次圖片識(shí)別api調(diào)用次數(shù),
開(kāi)通文字識(shí)別api地址如下https://console.cloud.tencent.com/ocr/overview,找不到的話在云產(chǎn)品下找通用文字識(shí)別
獲取api密鑰:https://console.cloud.tencent.com/cam/capi,如圖所示
2.安裝python環(huán)境
下載地址如下:https://www.python.org/downloads/,安裝過(guò)程需要選中添加環(huán)境變量,然后一路回車即可
win10菜單搜索【管理應(yīng)用執(zhí)行別名】關(guān)閉下面兩個(gè)按鈕【應(yīng)用安裝程序】,如下圖:
3.安裝相關(guān)的包
win建+cmd在命令行中運(yùn)行如下內(nèi)容:
python -m pip install --upgrade pip
pip install jupyter -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
pip install jupyterlab -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
pip install tencentcloud-sdk-python -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
jupyter lab --ip='*' --port=8888 --no-browser --allow-root
然后瀏覽器訪問(wèn)127.0.0.1:8888并輸入token,token位置如下:
4.目錄結(jié)構(gòu)
from目錄為原始圖片位置
to目錄為輸出txt文件夾位置
ipython為主程序文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-460613.html
新建ipython頁(yè)面并將代碼復(fù)制如下:
注:需要使用自己的SecretId和SecretKey替換這一行cred = credential.Credential(“SecretId”, “SecretKey”):文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-460613.html
import base64
import os
import json
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
def translate(image_base64):
try:
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "ocr.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = ocr_client.OcrClient(cred, "ap-shanghai", clientProfile)
req = models.EnglishOCRRequest()
params = {"ImageBase64": image_base64,
"Preprocess": True
}
req.from_json_string(json.dumps(params))
resp = client.EnglishOCR(req)
return json.loads(resp.to_json_string())
#print(resp.to_json_string())
except TencentCloudSDKException as err:
print(err)
image_dir = r'from'
txt_dir = r'to'
images= os.listdir(image_dir)
s = []
for image in images:
if not os.path.isdir(image):
image_path=image_dir+"/"+image
type1=str.lower(image_path.split(".")[1])
with open(image_path, 'rb') as f:
imagefile = f.read()
image_base64 = "data:image/"+type1+";base64,"+str(base64.b64encode(imagefile), encoding='utf-8')
dict1=translate(image_base64)
#print(dict1)
str1=''
for i in dict1['TextDetections']:
str1=str1+i['DetectedText']+'\n'
txt_path=txt_dir+"/"+image.split(".")[0]+".txt"
with open(txt_path, "w", encoding='utf-8') as f:
f.write(str(str1))
f.close()
#print(image_base64)
到了這里,關(guān)于利用騰訊云api實(shí)現(xiàn)手寫(xiě)字體識(shí)別的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!