简介:本文详细介绍如何申请百度文字识别API Key,包括注册百度智能云账号、实名认证、创建应用、获取密钥及调用示例,帮助开发者快速集成OCR服务。
百度文字识别(OCR)API 为开发者提供了高效、精准的文字识别能力,支持通用场景、身份证、银行卡、营业执照等多种类型的图片文字提取。要使用这一服务,首先需要申请 API Key 和 Secret Key,这是调用百度OCR接口的必备凭证。本文将详细介绍申请流程、注意事项及代码调用示例,帮助开发者快速上手。
在申请百度文字识别API Key之前,需完成以下基础准备:
访问百度智能云官网,使用百度账号登录。若未注册,需先完成注册流程。
获取API Key后,可通过HTTP请求调用OCR接口。以下以Python为例,展示如何调用通用文字识别API:
pip install requests
百度OCR API需使用Access Token进行身份验证,Token有效期为30天。生成Token的代码如下:
import requestsimport base64import hashlibimport jsonimport timedef get_access_token(api_key, secret_key):auth_url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}"response = requests.get(auth_url)if response.status_code == 200:return response.json().get("access_token")else:raise Exception("Failed to get access token")# 替换为你的API Key和Secret Keyapi_key = "your_api_key"secret_key = "your_secret_key"access_token = get_access_token(api_key, secret_key)print("Access Token:", access_token)
def ocr_general(access_token, image_path):ocr_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={access_token}"# 读取图片并转为Base64with open(image_path, "rb") as f:image_data = base64.b64encode(f.read()).decode("utf-8")headers = {"Content-Type": "application/x-www-form-urlencoded"}data = {"image": image_data}response = requests.post(ocr_url, headers=headers, data=data)if response.status_code == 200:return response.json()else:raise Exception("OCR API call failed")# 调用OCR接口image_path = "test.jpg" # 替换为你的图片路径result = ocr_general(access_token, image_path)print("OCR Result:", result)
OCR接口返回的JSON数据包含识别结果,例如:
{"log_id": 123456789,"words_result": [{"words": "百度文字识别"},{"words": "Hello World"}],"words_result_num": 2}
可通过遍历words_result数组获取识别出的文字。
申请百度文字识别API Key的流程包括注册账号、实名认证、创建应用及获取密钥。通过控制台可轻松完成配置,并结合代码示例快速调用OCR接口。开发者需注意密钥安全、调用频率限制及图片质量,以确保服务稳定运行。百度OCR API为文本识别提供了高效、可靠的解决方案,适用于多种业务场景。