python实现百度OCR图片识别过程解析

yipeiwu_com5年前Python基础

这篇文章主要介绍了python实现百度OCR图片识别过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

import base64
import requests

class CodeDemo:
  def __init__(self,AK,SK,code_url,img_path):
    self.AK=AK
    self.SK=SK
    self.code_url=code_url
    self.img_path=img_path
    self.access_token=self.get_access_token()

  def get_access_token(self):
    token_host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'.format(ak=self.AK,sk=self.SK)
    header={'Content-Type': 'application/json; charset=UTF-8'}
    response=requests.post(url=token_host,headers=header)
    content = response.json()
    access_token=content.get("access_token")
    return access_token

  def getCode(self):
    header = {
      "Content-Type": "application/x-www-form-urlencoded"
    }
    def read_img():
      with open(self.img_path, "rb")as f:
        return base64.b64encode(f.read()).decode()

    image = read_img()
    response=requests.post(url=self.code_url,data={"image":image,"access_token":self.access_token},headers=header)
    return response.json()

if __name__ == '__main__':
  AK = "" # 官网获取的AK
  SK = "" # 官网获取的SK
  code_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" # 百度图片识别接口地址
  img_path=r"" # 识别图片的地址

  code_obj=CodeDemo(AK=AK,SK=SK,code_url=code_url,img_path=img_path)
  res=code_obj.getCode()
  code=res.get("words_result")[0].get("words")
  print(res)
  print(code)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python循环输出三角形图案的例子

python循环输出三角形图案的例子

我就废话不多说了,直接上代码吧! #Copyright (c)2017, 东北大学软件学院学生 # All rightsreserved #文件名称:a.py #作 者:孔云 #问题...

python字符类型的一些方法小结

int 数字类型 class int(object): """ int(x=0) -> int or long int(x, base=10) -> int...

python3.5使用tkinter制作记事本

tkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单易用、与Python的结合度好。tkinter在Python...

Python入门篇之编程习惯与特点

1.代码风格 在Python中,每行程序以换行符代表结束,如果一行程序太长的话,可以用“\”符号扩展到下一行。在python中以三引号(""")括起来的字符串,列表,元组和字典都能跨行...

django 中QuerySet特性功能详解

Book表的数据显示 id title   price publish_id 2 Linux   30    1 3 项塔兰   45    2 4 追风筝的人...