个人调用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博客

相关推荐
程序员张小厨2 小时前
【0014】Python数据类型-元组类型详解
python·元组·python推导式·python元组·python元组数据类型·元组数据类型·python元组遍历
孟and平2 小时前
Flask 打包为exe 文件
后端·python·flask
天天进步20154 小时前
Python项目-基于Django的在线教育平台开发
python
大只因bug4 小时前
基于Django的协同过滤算法养老新闻推荐系统的设计与实现
后端·python·django·协同过滤算法推荐系统·新闻推荐网站系统·养老新闻推荐系统·个性化新闻推荐网站系统
勘察加熊人6 小时前
python将pdf转换成word
python·pdf·word
StevenLdh8 小时前
JAVA Spring Boot @Bean 注解的使用和注意事项
java·spring boot·python
大模型铲屎官8 小时前
Python 性能优化:从入门到精通的实用指南
开发语言·人工智能·pytorch·python·性能优化·llm·编程
莫忘初心丶9 小时前
uv:高性能 Python 包和项目管理工具使用教程
开发语言·python·uv
菜鸡66669 小时前
服务器python项目部署
服务器·开发语言·python
起个破名想半天了9 小时前
一招解决Pytorch GPU版本安装慢的问题
pytorch·python·深度学习