window环境下:
第一步:安装tesseract:教程如下:Windows环境安装tesseract-ocr 4.00并配置环境变量 - 简庆旺 - 博客园
第二步:安装 tesserocr : 到这里下载whl版本 https://github.com/simonflueckiger/tesserocr-windows_build/releases
然后在cmd下 pip install D:\Chromedowload\tesserocr-2.2.2-cp36-cp36m-win_amd64.whl
第三步:
import tesserocr
from PIL import Image
ima = Image.open('20180605095750237.png')
res = tesserocr.image_to_text(ima).strip()
print(res)
这样就可以获取到验证码中的文字了,然后把文字输入即可。
注意:正常情况下,这样的识别率是非常低的。需要对图片进行处理后,再识别。
完整的流程:
import tesserocr
from PIL import Image
image = Image.open('code2.jpg')
image = image.convert('L') # 转为灰度图像
threshold = 127 # #指定二值化的阈值
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1') # 进行二值化
image.show()
result = tesserocr.image_to_text(image)
print(result)
假设你的代码遇到报错:
“RuntimeError: Failed to init API, possibly an invalid tessdata path: ”
异常原因: 因为 python 找不到 tessdata 文件夹导致的。
解决办法: 找到自己安装 Te sseract-OCR的目录,将其中的 tessdata 复制一份到你的 python 目录文件夹中,放入与Lib同级目录中。