个人调用OCR

一、自己训练模型

二、调用现成API

此处介绍百度智能云API,因为有免费次数。(原来一些网址在百度不是默认显示网址的,而是自己的网站名字)

首页找到OCR

每个人每月能用1K次。(有详细的API文档说明,不过跟着我的步骤来也足够)

在创建应用后得到API key和 Secret Key

还需要拿到一个access token

python 复制代码
#官方代码
import requests
import json

def main():
        
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxx&client_secret=xxxxx"
    
    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text)

if __name__ == '__main__':
    main()

# 更改为个人使用版本
def get_token(self):
    url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s' \
           '&client_secret=%s' % (self.apikey,self.apisecret)
    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
        }
    response = requests.request("POST", url, headers=headers, data=payload)
    if response:
        print(response.json())
        # 存储token
        try:
            self.redis1["baidutoken"]=response.json()["access_token"]
        except Exception as e:
            print("请求报错,无法获取token")

全代码

python 复制代码
import requests
import base64
# 封装百度类
class Baidu:
    def __init__(self):
        # apikey 
        self.apikey = "12345"
        # api secretkey
        self.apisecret = "12345"
        self.redis = {} 
    # 文字图片识别
    def cor(self, filename=r"C:\Users\eqwimg\test.png"):
        # 定义请求地址
        request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
        # 读取图片
        f = open(filename, 'rb')
        # base64编码
        img = base64.b64encode(f.read())
        # 定义请求参数
        params = {"image": img}
        self.get_token()
        access_token = self.redis.get("baidutoken")
 
        request_url = request_url + "?access_token=" +access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        # 发起请求
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            print(response.json())
            # 获取识别的结果
            num = ""
            for x in response.json()["words_result"]:
                num += x["words"]
            return num
    # 获取token
    def get_token(self):
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s' \
               '&client_secret=%s' % (self.apikey,self.apisecret)
        response = requests.get(host)
        payload = ""
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
            }
        response = requests.request("POST", url, headers=headers, data=payload)
        if response:
            print(response.json())
            # 存储token
            try:
                self.redis["baidutoken"]=response.json()["access_token"]
            except Exception as e:
                print("请求报错,无法获取token")
def cor():
    # 实例化对象
    baidu = Baidu()
    num = baidu.cor()
    times = 0
    success = False
    while times<3 and not success:#最大识别3次
        num = baidu.cor()
        if len(num) == 4:  #默认是4为识别码
            success = True
        else:
            break
        times += 1
    if success:
        return num
    else:
        return None
cor()

借鉴:

https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

selenium--自动化识别图片验证码并输入_selenium识别验证码图片-CSDN博客

相关推荐
Emma歌小白18 分钟前
JavaScript (JS) 和 Python 语法对比
python
梓羽玩Python41 分钟前
开源AI代理爆火!Suna:3天内新增5.5K+标星,自然对话驱动的自动化神器!
人工智能·python·github
咖啡调调。1 小时前
模板引擎语法-过滤器
python·django·sqlite
Ankie Wan1 小时前
notepad++技巧:查找和替换:扩展 or 正则表达式
python·正则表达式·notepad++
带娃的IT创业者1 小时前
《AI大模型趣味实战》智能Agent和MCP协议的应用实例:搭建一个能阅读DOC文件并实时显示润色改写过程的Python Flask应用
人工智能·python·flask
JavaEdge在掘金1 小时前
启动nginx报错,80 failed (97: Address family not supported by protocol)
python
纪元A梦1 小时前
华为OD机试真题——绘图机器(2025A卷:100分)Java/python/JavaScript/C++/C/GO最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
程序员小远1 小时前
接口测试和单元测试详解
自动化测试·软件测试·python·测试工具·单元测试·测试用例·接口测试
Tech Synapse2 小时前
电商商品推荐系统实战:基于TensorFlow Recommenders构建智能推荐引擎
人工智能·python·tensorflow
聿小翼2 小时前
selenium-wire 与 googletrans 的爱恨情仇
python