帮我写一下使用Python调用移动云ocr的代码
时间: 2023-06-26 21:04:38 浏览: 140
好的,以下是使用Python调用移动云OCR的代码:
```python
import requests
import base64
# 替换成你的API Key和Secret Key
api_key = 'your_api_key'
secret_key = 'your_secret_key'
# 获取access token
def get_access_token(api_key, secret_key):
token_url = 'https://aip.baidubce.com/oauth/2.0/token'
params = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': secret_key
}
response = requests.post(token_url, params=params)
if response.status_code == 200:
return response.json()['access_token']
else:
return None
# 调用OCR接口
def ocr(image_path):
access_token = get_access_token(api_key, secret_key)
ocr_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
with open(image_path, 'rb') as f:
image_data = base64.b64encode(f.read()).decode('ascii')
data = {'image': image_data}
params = {'access_token': access_token}
response = requests.post(ocr_url, params=params, headers=headers, data=data)
if response.status_code == 200:
result = response.json()
words_result = result.get('words_result', [])
text = ''.join([w['words'] for w in words_result])
return text
else:
return None
# 调用示例
image_path = 'test.jpg'
text = ocr(image_path)
print(text)
```
其中,`api_key`和`secret_key`需要替换成你自己的API Key和Secret Key,`image_path`是需要识别的图片路径。调用示例中,我们将识别结果打印出来。
阅读全文
相关推荐
















