python文字识别

这篇博客介绍了如何通过Python代码调用百度AI的文字识别服务,特别是针对手写文字的OCR功能。首先,访问百度AI控制台创建应用获取API_KEY和SECRET_KEY。然后,利用提供的代码示例展示如何读取图片并发送请求进行识别,最后打印出识别出的文本。此过程涉及基础的HTTP请求、JSON解析和Base64编码。
摘要由CSDN通过智能技术生成

 

1.访问 https://console.bce.baidu.com/#/index/overview_v3

2.打开产品服务,选择文字识别

        

3.点击创建应用

        

4.代码部分    

import requests
import json
import base64




def get_file_content(filePath):
   """ 读取图片base64 """
   with open(filePath, 'rb') as fp:
      return base64.b64encode(fp.read())




def get_access_token():
   # API_Key,Secret_Key 需要在 https://console.bce.baidu.com/ai/?fromai=1#/ai/ocr/app/list 创建应用才能获得
   API_Key = 'app_key
   Secret_Key = 'Secret_Key'
   r = requests.post('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+API_Key+'&client_secret='+Secret_Key)
   j = json.loads(r.text)
   access_token = j.get('access_token')
   return access_token




def recognise_handwriting_pic(access_token,image_path):
   image = get_file_content(image_path)
   r = requests.post(
      url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token='+access_token,
      headers={"Content-Type":"application/x-www-form-urlencoded"},
      data = {'image':image})
   j = json.loads(r.text)
   words_result = j.get('words_result')
   for i in words_result:
      print(i.get('words'))


access_token = get_access_token()  # 获取一次保存下来就够了,一般1个月有效期

recognise_handwriting_pic(access_token,image_path='./static/img/test.jpg')
recognise_handwriting_pic(access_token,image_path='./static/img/hander.jpg')

示例

 

结果

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值