当前位置: 首页 > java >正文

百度ocr的简单封装

百度ocr地址

以下代码为对百度ocr的简单封装,实际使用时推荐使用baidu-aip

百度通用ocr

import base64
from enum import Enum, unique
import requests
import logging as log@unique
class OcrType(Enum):# 标准版STANDARD_BASIC = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"# 标准版含位置STANDARD_WITH_LOCATION = "https://aip.baidubce.com/rest/2.0/ocr/v1/general"# 高精度版ACCURATE_BASIC = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"# 高精度版含位置ACCURATE_WITH_LOCATION = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate"# 办公文档识别DOC_ANALYSiS_OFFICE = "https://aip.baidubce.com/rest/2.0/ocr/v1/doc_analysis_office"# 网络图片文字识别WEB_IMAGE = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage"# 网络图片文字识别 含位置WEB_IMAGE_WITH_LOCATION = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage_loc"# 手写文字识别HAND_WRITING = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting"# 数字识别NUMBERS = "https://aip.baidubce.com/rest/2.0/ocr/v1/numbers"# 表格文字识别(同步接口)FORM_SYNCH = "https://aip.baidubce.com/rest/2.0/ocr/v1/form"# 表格文字识别(异步接口)FORM_ASYNCH = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request"# 二维码识别QRCORD = "https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode"def ocr_help():print("==========百度ocr使用说明==========")print("本API基于ocr通用识别api编写,官方文档地址:https://cloud.baidu.com/doc/OCR/s/zk3h7xz52")print("使用示例:")print('''baiduOcr = BaiduGeneralOcr(OcrType.STANDARD_BASIC)baiduOcr.set_access_token("access_token")wordsList = baiduOcr.recoginze(image="D:\\txt1.png",options={})['words_result']for word in wordsList:print(word)''')class BaiduGeneralOcr():# ocr版本ocr_type = 0def __init__(self, ocr_type: OcrType):"""ocr_type ocr识别类型 STANDARD_BASIC标准版 标准版含位置STANDARD_WITH_LOCATION 高精读版ACCURATE_BASIC 高精度版含位置ACCURATE_WITH_LOCATION@param ocr_type:"""self.options = Noneself.pdf_file = Noneself.url = Noneself.image = Noneself.access_token = Noneself.ocr_type = ocr_type.valuedef gen_access_token(self, api_key, secret_key):"""生成access_token@param api_key:@param secret_key:@return:"""request_url = f'''https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}'''response = requests.get(request_url)if response:print("access_token:%s" %(response.json()['access_token']))self.access_token = response.json()['access_token']def __check(self):"""参数检查@return:"""image = self.imageurl = self.urlpdf_file = self.pdf_fileif (image is None or image == "") and (url is None or url == "") and (pdf_file is None or pdf_file == ""):raise ValueError("image,url,pdf_file至少传入一项")if (image is not None) and (image != ""):f = open(image, 'rb')self.options['image'] = base64.b64encode(f.read()).decode()elif (image is not None or image == "") and (url is not None and url != ""):self.options['url'] = urlelse:f = open(pdf_file, 'rb')self.options['pdf_file'] = base64.b64encode(f.read()).decode()keys = self.options.keys()if ("image" not in keys) and ("url" not in keys) and ("pdf_file" not in keys):raise ValueError("image,url,pdf_file至少传入一项")try:self.ocr_type.valueexcept Exception as e:log.info(repr(e))self.ocr_type = OcrType.STANDARD_BASIClog.info("ocr_type类型,已重置为标准版")def __request(self, request_url, data):# 设置headerheaders = {'content-type': 'application/x-www-form-urlencoded'}# 请求print(self.options)print(headers)return requests.post(request_url + "?access_token=%s" % self.access_token, data=self.options,headers=headers).json()def recoginze(self, image: str = None, url: str = None, pdf_file: str = None, options=None):"""识别@param image:@param url:@param pdf_file:@param options:@return:"""self.image = imageself.url = urlself.pdf_file = pdf_fileself.options = options or {}self.__check()# 发送请求return self.__request(self.ocr_type.value, options)def set_access_token(self, access_token):"""设置access_token@param access_token:@return:"""self.access_token = access_token

百度卡片识别ocr

import requests
import base64
import json
from cwrpa.log.log import logging as log
from enum import Enum, unique
import keyring@unique
class OcrType(Enum):# 身份证识别ID_CARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"# 身份证混贴识别MULTI_IDCARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/multi_idcard"# 身份证识别(金融加密版)IDCARD_ENC = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard_enc"# 银行卡识别BANKCARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard"# 营业执照识别BUSINESS_LICENSE = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"# 名片识别BUSINESS_CARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_card"# 护照识别PASSPORT = "https://aip.baidubce.com/rest/2.0/ocr/v1/passport"# 社保卡识别SOCIAL_SECURITY_CARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/social_security_card"# 港澳通行证识别HK_MACAU_EXITENTRYPERMIT = "https://aip.baidubce.com/rest/2.0/ocr/v1/HK_Macau_exitentrypermit"# 台湾通行证识别TAIWAN_EXITENTRYPERMIT = " https://aip.baidubce.com/rest/2.0/ocr/v1/taiwan_exitentrypermit"# 户口本识别HOUSEHOLD_REGISTER = "https://aip.baidubce.com/rest/2.0/ocr/v1/household_register"# 出生医学识别证明BITTH_CERTIFICATE = "https://aip.baidubce.com/rest/2.0/ocr/v1/birth_certificate"# 多卡证类别检测MULTI_CARD_CLASSIFY = "https://aip.baidubce.com/rest/2.0/ocr/v1/multi_card_classify"def ocr_help():print("==========百度ocr使用说明==========")print("本API基于ocr卡证识别api编写,官方文档地址:https://ai.baidu.com/ai-doc/OCR/rk3h7xzck")print("使用示例:")print('''baiduOcr = BaiduCardOcr(OcrType.ID_CARD)baiduOcr.set_access_token("access_token")wordsList = baiduOcr.recoginze(image="D:\\txt1.png",options={})['words_result']for word in wordsList:print(word)''')class BaiduCardOcr:# ocr版本ocr_type = 0def __init__(self, ocr_type: OcrType):"""ocr_type ocr识别类型 STANDARD_BASIC标准版 标准版含位置STANDARD_WITH_LOCATION 高精读版ACCURATE_BASIC 高精度版含位置ACCURATE_WITH_LOCATION@param ocr_type:"""self.options = Noneself.pdf_file = Noneself.url = Noneself.image = Noneself.access_token = Noneself.ocr_type = ocr_type.valuedef gen_access_token(self, api_key, secret_key):"""生成access_token@param api_key:@param secret_key:@return:"""request_url = f'''https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}'''response = requests.get(request_url)if response:self.access_token = response.json()['access_token']def __check(self):"""参数检查@return:"""image = self.imageurl = self.urlpdf_file = self.pdf_fileif (image is None or image == "") and (url is None or url == "") and (pdf_file is None or pdf_file == ""):raise ValueError("image,url,pdf_file至少传入一项")if (image is not None) and (image != ""):f = open(image, 'rb')self.options['image'] = base64.b64encode(f.read()).decode()elif (image is not None or image == "") and (url is not None and url != ""):self.options['url'] = urlelse:f = open(pdf_file, 'rb')self.options['pdf_file'] = base64.b64encode(f.read()).decode()keys = self.options.keys()if ("image" not in keys) and ("url" not in keys) and ("pdf_file" not in keys):raise ValueError("image,url,pdf_file至少传入一项")try:self.ocr_type.valueexcept Exception as e:log.info(repr(e))self.ocr_type = OcrType.STANDARD_BASIClog.info("ocr_type类型,已重置为标准版")def __request(self, request_url, data):# 设置headerheaders = {'content-type': 'application/x-www-form-urlencoded'}# 请求print(self.options)print(headers)return requests.post(request_url + "?access_token=%s" % self.access_token, data=self.options,headers=headers).json()def recoginze(self, image: str = None, url: str = None, pdf_file: str = None, options=None):"""识别@param image:@param url:@param pdf_file:@param options:@return:"""self.image = imageself.url = urlself.pdf_file = pdf_fileself.options = options or {}self.__check()# 发送请求return self.__request(self.ocr_type.value, options)def set_access_token(self, access_token):"""设置access_token@param access_token:@return:"""self.access_token = access_token
http://www.xdnf.cn/news/9156.html

相关文章:

  • html5视频播放器和微信小程序如何实现视频的自动播放功能
  • 优雅草最新实战项目技术Discuz X3.5电子签约插件开发项目实施方案优雅草·卓伊凡
  • MicroPython 开发ESP32应用教程 之 线程介绍及实例分析
  • Android 启动优化
  • 使用堡塔和XShell
  • C++ STL stack容器使用详解
  • IoT/HCIP实验-1/物联网开发平台实验Part1(快速入门,MQTT.fx对接IoTDA)
  • 大型三甲医院更换HIS系统全流程分析与经验考察(上)
  • 【教程】给Apache服务器装上轻量级的防DDoS模块
  • 【HarmonyOS Next之旅】DevEco Studio使用指南(二十七) -> 开发云函数
  • 基于 SpringBoot 与 VueJS 的智慧就业服务平台构建:技术融合与实践创新
  • jsAPI:Intl.DateTimeFormat 属性含义
  • 尚硅谷redis7 37-39 redis持久化之AOF简介
  • Vuex 模块化和命名空间:管理大型应用的状态
  • 【MYSQL】Linux下安装mysql 8,rpm包方式安装(保姆篇)
  • 【数据插入最大值后】2022-2-2
  • 【Redis】第2节|Redis基本数据类型
  • 信息学奥赛一本通 1547:【 例 1】区间和
  • 算法-全排列
  • 怎么预测体育比赛的胜率?
  • 曲线匹配,让数据点在匹配数据的一侧?
  • 第12次06 :用户中心添加邮箱
  • 【01】大模型原理与API使用
  • 【本地面板公网访问】本地面板也能公网访问?CasaOS+1Panel+cpolar保姆级教程
  • GeoServer样式设置:使用本地图标及分层/分视野显示
  • linux中使用make clean重新编译
  • 3dmax直接导入导出gltf/glb格式插件(免费)
  • 链表面试题10之随机链表的复制
  • Windows环境下Redis的安装使用与报错解决
  • DeepSpeed-Ulysses:支持极长序列 Transformer 模型训练的系统优化方法