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设计】。

相关文章

Python3.5 Json与pickle实现数据序列化与反序列化操作示例

Python3.5 Json与pickle实现数据序列化与反序列化操作示例

本文实例讲述了Python3.5 Json与pickle实现数据序列化与反序列化操作。分享给大家供大家参考,具体如下: 1、Json:不同语言之间进行数据交互。 (1)JSON数据序列化...

Python中的if、else、elif语句用法简明讲解

下面我们学习if语句,输入下面的代码,确保能够正确运行。 people = 20 cats = 30 dogs = 15 if people < cats:...

WIn10+Anaconda环境下安装PyTorch(避坑指南)

WIn10+Anaconda环境下安装PyTorch(避坑指南)

这些天安装 PyTorch,遇到了一些坑,特此总结一下,以免忘记。分享给大家。 首先,安装环境是:操作系统 Win10,已经预先暗转了 Anaconda。 1. 为 PyTorch 创建...

python中利用zfill方法自动给数字前面补0

python中利用zfill方法自动给数字前面补0

python中有一个zfill方法用来给字符串前面补0,非常有用 view sourceprint? n = "123" s = n.zfill(5) assert s...

Python 2.x如何设置命令执行的超时时间实例

前言 在Python2.x中的几个用来执行命令行的库或函数在执行命令是均不能设置一个命令执行的超时时间,用来在命令执行时间超时时终端这个命令的执行,这个功能在3.x(?)中解决了,但是在...