python 调用百度API 完成本地硬盘图片OCR 文字识别,代码
以下是一个基于 Python 和百度API的本地硬盘图片OCR文字识别的示例代码:
import requests
import base64
import json
# 百度API的相关信息
api_key = 'your_api_key'
secret_key = 'your_secret_key'
ocr_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
# 打开本地图片文件,读取二进制数据
with open('image.jpg', 'rb') as f:
image_data = f.read()
# 将图片数据进行base64编码
image_base64 = base64.b64encode(image_data)
# 构建请求参数
params = {
'image': image_base64,
'language_type': 'CHN_ENG',
}
# 添加身份认证信息
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
auth_data = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': secret_key,
}
auth_url = 'https://aip.baidubce.com/oauth/2.0/token'
auth_response = requests.post(auth_url, data=auth_data)
access_token = json.loads(auth_response.text)['access_token']
headers['Authorization'] = 'Bearer ' + access_token
# 发送请求,获取识别结果
response = requests.post(ocr_url, headers=headers, data=params)
if response.status_code == 200:
result = json.loads(response.text)
if 'words_result' in result:
for item in result['words_result']:
print(item['words'])
else:
print('未识别到文字')
else:
print('请求出错,错误码:%d' % response.status_code)
在代码中,首先需要将本地的图片文件读取成二进制数据,然后将其进行base64编码。接着构建请求参数,包括图片数据和识别语言类型等信息。然后需要进行身份认证,获取access_token,添加到请求头中。最后发送POST请求,得到识别结果。如果识别成功,则输出识别结果;如果失败,则输出错误信息。
原文地址: https://www.cveoy.top/t/topic/wNO 著作权归作者所有。请勿转载和采集!