Python3 调用阿里巴巴AI,进行文字识别

import os
import base64
import requests
from dataclasses import dataclass

def get_img_base64str(image_file):
    """生成原始图片的base64编码数据,得到image参数"""
    if not isinstance(image_file, str):
        return None
    if not os.path.isfile(image_file):
        print ('图片文件有误,请传入正确的文件路径')
        return None
    with open(image_file, 'rb') as fp:
        imgbase64 = base64.b64encode(fp.read())
        return imgbase64.decode()

@dataclass
class AliAPIMsg(object):
    appcode:      str
    api_url:      str
    image_file:   str

    def __post_init__(self):
        self.image   = get_img_base64str(self.image_file)
        self.headers = {'Authorization': 'APPCODE ' + self.appcode, }
        self.data    = {
            'image': self.image,
            "configure": {'minsize': 16,
                          'output_prob': True, }, }

    def get_ocr_result(self):
        res = requests.post(self.api_url, headers=self.headers, json=self.data)
        try:
            res_data = res.json()
            word_list = [word['word'] for word in res_data['ret']]
            text =  '\n'.join(word_list)
        except:
            print('获取结果失败,请检查各参数是否配置正确。')
            text = ''
        return text

if __name__ == "__main__":
    appcode = 'a******************************8'  # 需要自己购买申请
    api_url = "https://tysbgpu.market.alicloudapi.com/api/predict/ocr_general"
    image_file = 'F:\\20180829193608871.jpg'

    Ali = AliAPIMsg(appcode, api_url, image_file)
    result = Ali.get_ocr_result()
    print(result)

猜你喜欢

转载自blog.csdn.net/qq523176585/article/details/88853692