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中,总的来说有三种大的模式打开文件,分别是:a, w, r 当以a模式打开时,只能写文件,而且是在文件末尾添加内容。 当以a+模式打开时,可以写文件,也可读文件,可是在读文...

python数据结构学习之实现线性表的顺序

python数据结构学习之实现线性表的顺序

本文实例为大家分享了python实现线性表顺序的具体代码,供大家参考,具体内容如下 线性表 1.抽象数据类型表示(ADT) 类型名称:线性表 数据对象集:线性表是n(>=0)个元...

python实现桌面壁纸切换功能

本文实例为大家分享了python实现桌面壁纸切换功能的具体实现方法,供大家参考,具体内容如下 大体分为两个部分 一、利用爬虫爬取壁纸 第一部分爬取图片url地址并且下载至本地 爬虫针对...

Python中操作MySQL入门实例

一、安装MySQL-python 复制代码 代码如下: # yum install -y MySQL-python 二、打开数据库连接 复制代码 代码如下: #!/usr/bin/py...

python持久性管理pickle模块详细介绍

持久性就是指保持对象,甚至在多次执行同一程序之间也保持对象。通过本文,您会对 Python对象的各种持久性机制(从关系数据库到 Python 的 pickle以及其它机制)有一个总体认识...