Python 识别验证码

3,181 阅读2分钟
原文链接: www.jianshu.com
  • 首先,打开命令行或者终端,输入以下命令:

    virtualenv venv --no-site-packages --python=X:\xxx\python.exe

    各参数解释:

    • venv 虚拟环境所在位置
    • --no-site-packages 不复制主环境的库
    • --python 指定虚拟环境的 python 版本

    然后在命令行输入以下命令,激活虚拟环境

    • Linux
      cd venv
      source ./bin/activate
    • Windows
      cd venv
      .\Scripts\activate

    如果要退出虚拟环境的话则输入

    deactivate
    或
    .\Scripts\deactivate
  • 安装依赖包
    在当前虚拟环境中输入

    pip install PIL
    pip install Pillow
    pip install pytesseract

    安装完成后进入python,import一下看是否安装成功。

  • 图片处理


    Captcha.jpg

    from PIL import Image
    im = Image.open('Captcha.jpg')
    im = im.convert('L')

    转化为灰度图是为了减少图片的色彩,处理起来更方便

    为了消除背景对文字的影响,可以通过设置一个阈值来将文字与背景分隔开来。而阈值可以参考图片灰度的直方图来得出,又或者试出来。

    这里将阈值设置为 140,然后将大于阈值的像素置 1,小于阈值的置 0。

    def initTable(threshold=140):
     table = []
     for i in range(256):
         if i < threshold:
             table.append(0)
         else:
             table.append(1)
    
     return table

    再使用 im.point() 可以将灰度图二值化,结果如下:

    binaryImage = im.point(initTable(), '1')
    binaryImage.show()

    Captcha1.jpg

  • 识别文本

    可以通过 pytesseract 的 image_to_string() 函数将图片转化为文本,该函数还可以接受参数 config,config 设置的是 Tesseract-OCR 引擎的参数,可自行查阅引擎的帮助文本。不过我们只需要用到 psm 参数,具体的 psm 参数值如下:

    -psm N
      Set Tesseract to only run a subset of layout analysis and assume a certain form of image. The options for N are:
    
      0 = Orientation and script detection (OSD) only.
      1 = Automatic page segmentation with OSD.
      2 = Automatic page segmentation, but no OSD, or OCR.
      3 = Fully automatic page segmentation, but no OSD. (Default)
      4 = Assume a single column of text of variable sizes.
      5 = Assume a single uniform block of vertically aligned text.
      6 = Assume a single uniform block of text.
      7 = Treat the image as a single text line.
      8 = Treat the image as a single word.
      9 = Treat the image as a single word in a circle.
      10 = Treat the image as a single character.

    识别图片的代码如下:

    print(image_to_string(binaryImage, config='-psm 7')

    识别结果为

    7226
  • 误差修正

    经过测试发现,Tesseract-OCR 对于纯数字的验证码识别有一定误差,因为该引擎识别的是英文文本,所以会将数字识别为字母。这时候就需要建立一个替换表,将识别错误的字母替换为数字,提高识别正确率。