python-使用百度接口进行OCR

2023-05-16

1.先按照百度的接口模块

pip install baidu-aip

要是速度慢的话,直接使用清华源的安装方式

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple baidu-aip

2.运行以下代码,可以得到的是百度识别后的字符串,不画框

# 新建AipOCR
from aip import AipOcr

config = {
    'appId': '16158078',
    'apiKey': 'DddGkqgGI4xTYvwKDLwfVIRu',
    'secretKey': 'iFGskCPGASquQbDD0ikOfeFTuOVcYyUZ'
}

client = AipOcr(**config)

def get_file_content(file):
    with open(file, 'rb') as fp:
        return fp.read()

def img_to_str(image_path):
    image = get_file_content(image_path)
    result = client.basicGeneral(image)
    if 'words_result' in result:
        return '\n'.join([w['words'] for w in result['words_result']])

if __name__ == '__main__' :
    imagepath = 'test.jpg'
    str = img_to_str(imagepath)
    print(str)

3.运行以下代码可以得到带画框的效果

import cv2
from aip import AipOcr

""" 你的 APPID AK SK  图2的内容"""
APP_ID = '16158078'
API_KEY = 'DddGkqgGI4xTYvwKDLwfVIRu'
SECRET_KEY = 'iFGskCPGASquQbDD0ikOfeFTuOVcYyUZ'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

fname = 'test.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)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python-使用百度接口进行OCR 的相关文章

随机推荐