背景
在处理效能提升的某个项目时,遇到一个验证码的问题,开始使用的是需要 pillow 和 pytesseract 这两个库,但是识别率不高,有时还会识别不出来。又不想单独处理躁点相关的问题,于是使用到了其他的OCR库。
pytesseract经常会遇到如下图所示的效果
使用ddddocr
要求python >= 3.8,实际我用的是3.11
安装 pip install ddddocr
说明:使用pip install ddddocr 安装的版本可能会很低,我安装的时候是1.0.6,ddddocr.DdddOcr(show_ad=False) 会报错,需要更新下版本,可使用 pip install ddddocr -i pypi.tuna.tsinghua.edu.cn/simple/
import ddddocr
def get_captcha_url():
url = "url/api/base/captcha"
payload = {}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
# 请求验证码链接,处理captchaId,用于login
logger.info("请求验证码链接返回的数据--->"+str(response.content))
captchaId = response.json()["data"]["captchaId"]
# print(captchaId)
# 数据使用split 进行切割
picdata = response.json()["data"]["picPath"].split(",")[1]
# picdata需要先进行base64解码
decoded_data = base64.b64decode(picdata)
# 将解析出来的数据,写入图片
with open(r'D:\code\auto_user\common\saveImg\captcha.png', 'wb') as f:
f.write(decoded_data)
ocr = ddddocr.DdddOcr(show_ad=False)
with open(r'D:\code\auto_user\common\saveImg\captcha.png', 'rb') as f:
img_bytes = f.read()
picPath = ocr.classification(img_bytes)
# print(res)
if picPath is None:
# print("captcha数据为空")
logger.info("captcha数据为空")
# print("文字验证码:", picPath)
logger.info("文字验证码:"+picPath)
return picPath, captchaId
效果