python调用百度ai将图片识别为表格excel

python调用百度ai将图片识别为表格excel

ocr

百度ai官方文档:https://ai.baidu.com/ai-doc/OCR/Ik3h7y238

python 复制代码
import requests
import json
import base64
import time
'''
文档:https://ai.baidu.com/ai-doc/OCR/Ik3h7y238
'''

# 获取access_token
def get_access_token():
    client_id = "xxxxxxxxxxxxxxxxxx"
    client_secret = "xxxxxxxxxxxxxxxxxxxxxx"
    # client_id = '你的apikey'
    # client_secret = '你的Secret Key'
    # client_id 为官网获取的AK, client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(
        client_id, client_secret)
    response = requests.get(host).text
    data = json.loads(response)
    access_token = data['access_token']
    return access_token


# 获取返回信息

# 获取识别结果
def get_info(access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request"
    # 二进制方式打开图片文件
    f = open('1.jpg', 'rb')
    img = base64.b64encode(f.read())  # base64编码
    params = {"image": img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    # if response:
    #     print(response.json())
    data_1 = response.json()
    return data_1


# 获取excel


def get_excel(requests_id, access_token):
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    pargams = {
        'request_id': requests_id,
        'result_type': 'excel'
    }
    url = 'https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result'
    url_all = url + "?access_token=" + access_token
    res = requests.post(url_all, headers=headers, params=pargams)  # 访问链接获取excel下载页
    info_1 = res.json()['result']['ret_msg']
    excel_url = res.json()['result']['result_data']
    excel_1 = requests.get(excel_url).content
    print(excel_1)
    with open('识别结果.xls', 'wb+') as f:
        f.write(excel_1)
    print(info_1)


def main():
    print('正在处理中请稍后')
    access_token = get_access_token()
    data_1 = get_info(access_token)
    try:
        requests_id = data_1['result'][0]['request_id']
        if requests_id != '':
            print('识别完成')
    except:
        print('识别错误')
    print('正在获取excel')
    time.sleep(10)  # 延时十秒让网页图片转excel完毕,excel量多的话,转化会慢,可以延时长一点
    get_excel(requests_id, access_token)


main()
相关推荐
GetcharZp7 小时前
让照片开口说话:LivePortrait 本地部署玩法详解
人工智能·计算机视觉
OpenCSG8 小时前
CSGClaw v0.4.2-v0.4.3 版本更新
人工智能·opencsg
大鱼>8 小时前
因子挖掘+回测+RL交易:量化金融完整系统
人工智能·深度学习·算法·金融
梦想三三8 小时前
YOLOv5 口罩目标检测实战(一):项目整体介绍与数据准备
人工智能·yolo·目标检测
梵构广告8 小时前
平台怎么做品牌营销策划?—品牌营销
大数据·人工智能·平面·品牌策划
编程阿峰8 小时前
Python 环境配置(二)安装jupyter、matplotlib、numpy库
开发语言·python·jupyter·numpy·matplotlib
土豆12508 小时前
DeepSeek V4-Flash 正式版深度解读:一行 changelog 里的暗涌与野心
人工智能·llm
AC赳赳老秦8 小时前
CSDN 技术社区数据采集:OpenClaw 抓取公开技术热帖,生成领域技术热点周报
java·大数据·前端·数据库·python·php·openclaw
Aloudata8 小时前
Prompt 驱动分析 vs Skill 驱动分析:企业 AI 分析如何从会问走向可复用
大数据·人工智能·数据分析·prompt·skill·语义层