调用百度ocr的API,python简易版本

调用百度ocr的API,python简易版本

https://www.jianshu.com/p/e10dc43c38d0

1. 注册

百度云注册帐号 https://cloud.baidu.com/?from=console
管理应用 https://console.bce.baidu.com/ai/#/ai/ocr/overview/index 建立一个
python

 
图1登录以后的界面

进入连接以后建立应用,因为是从文字识别点进去的,因此默认选中的就是ocr相关内容,填好表格确认。
 
图2 建立应用以后的界面

有了这三个东西,AppID 、API Key、Secret Key,咱们就能够在代码里调用接口了。

 

2. 调用API

官方指南:https://ai.baidu.com/docs#/OCR-Python-SDK/top
安装使用Python SDK: pip install baidu-aip
cv2 须要安装:pip install opencv_python
若是只须要预测文字以及框出文字区域,执行如下代码便可。spa

import cv2
from aip import AipOcr

""" 你的 APPID AK SK 图2的内容"""
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)

""" 调用通用文字识别, 图片参数为本地图片 """
results = client.general(image)["words_result"]  # 还可使用身份证驾驶证模板,直接获得字典对应所需字段

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)

斜必定角度也能检测出来 还不错code


 
效果图
相关文章
相关标签/搜索