运行环境:
Python3.11
Windows10操作系统
baidu-aip 4.16.11
from aip import AipOcr
def get_file_content(filePath):
"""
输入图片路径,返回图片的二进制码
:param filePath: 图片路径
:return:图片的二进制码
"""
with open(filePath, 'rb') as fp:
return fp.read()
def init():
"""
初始化,构造ocr对象
:return:
"""
# 从百度ocr申请的ID、Key和Secret_key
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
# 构造对象
return AipOcr(APP_ID, API_KEY, SECRET_KEY)
def verify_cap(image_path):
"""
获取验证码
:param image_path: 验证码图片路径
"""
client = init()
# 获取二进制码
image_byte = get_file_content(image_path)
# 进行识别,返回一个dict
result = client.basicGeneral(image_byte)
# 输出返回值字典
for key in result.items():
print(key)
captcha = ''
# 根据识别出的结果数量判断
if result['words_result_num'] == 0:
print('未识别出验证码!')
else:
# 存在多个返回值,则进行拼接
for key in result['words_result']:
captcha = captcha + key["words"]
# 去除验证码中的空格
captcha = captcha.replace(' ', '')
print('验证码:', captcha)
return captcha
print(verify_cap(r'C:\Users\Administrator\Desktop\yzm1.png'))