百度OCR api调用代码

import requests
import json
import base64, urllib
API_KEY = 'xx'
SECRECT_KEY = 'xx'
pic_name = "img.jpg"

def ocr_baidu():
    """invoke token"""
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    body = {'grant_type': 'client_credentials',
            'client_id': API_KEY,
            'client_secret': SECRECT_KEY
            }
    req = requests.post(url=url, data=body)
    token = json.loads(req.content)['access_token']
    """use token call BAIDU ocr api"""
    ocr_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%s' % token
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    body = base64.b64encode(open(pic_name, "rb").read())
    data = urllib.parse.urlencode({'image': body})
    r = requests.post(url=ocr_url, headers=headers, data=data)
    res_words = json.loads(r.content)['words_result']
    return res_words


if __name__ == '__main__':
    for i in ocr_baidu():
        print(i['words'])

你可能感兴趣的:(百度,ocr,python)