簡(jiǎn)化版本,只是在本地python調(diào)用,保存圖片在本地。
1. 注冊(cè)
百度云注冊(cè)賬號(hào) https://cloud.baidu.com/?from=console
管理應(yīng)用 https://console.bce.baidu.com/ai/#/ai/ocr/overview/index 創(chuàng)建一個(gè)

圖1登陸之后的界面
進(jìn)入鏈接之后創(chuàng)建應(yīng)用,由于是從文字識(shí)別點(diǎn)進(jìn)去的,所以默認(rèn)選中的就是ocr相關(guān)內(nèi)容,填好表格確認(rèn)。

圖2 創(chuàng)建應(yīng)用之后的界面
有了這三個(gè)東西,AppID 、API Key、Secret Key,我們就可以在代碼里調(diào)用接口了。
2. 調(diào)用API
官方指南:https://ai.baidu.com/docs#/OCR-Python-SDK/top
安裝使用Python SDK: pip install baidu-aip
cv2 需要安裝:pip install opencv_python
如果只需要預(yù)測(cè)文字以及框出文字區(qū)域,執(zhí)行以下代碼即可。
import cv2
from aip import AipOcr
""" 你的 APPID AK SK 圖2的內(nèi)容"""
APP_ID = '14318340'
API_KEY = 'DUvK5jEkNmCIEz4cXH8VvIVC'
SECRET_KEY = '*******'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
fname = 'picture/test4.jpg'
""" 讀取圖片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content(fname)
""" 調(diào)用通用文字識(shí)別, 圖片參數(shù)為本地圖片 """
results = client.general(image)["words_result"] # 還可以使用身份證駕駛證模板,直接得到字典對(duì)應(yīng)所需字段
img = cv2.imread(fname)
for result in results:
text = result["words"]
location = result["location"]
print(text)
# 畫矩形框
cv2.rectangle(img, (location["left"],location["top"]), (location["left"]+location["width"],location["top"]+location["height"]), (0,255,0), 2)
cv2.imwrite(fname[:-4]+"_result.jpg", img)
斜一定角度也能檢測(cè)出來 還不錯(cuò)

效果圖