python识别图片验证码

http://robertgawron.blogspot.hk/2010/11/almost-all-sites-use-images-with-text.html

http://code.google.com/p/python-tesseract/


图片的识别主要有,去色,减噪,去线,分割,二值化,提取特征码

这里比较方便的是使用tesseract



1,准备库

apt-get install python-imaging

pip install Pillow


apt-get install tesseract-ocr

apt-get -f iinstall


wget https://python-tesseract.googlecode.com/files/python-tesseract_0.8-1.5_i386.deb

dpkg -i python-tesseract_0.8-1.5_i386.deb

2,图片处理


这里用到Pillow代替PIL,import改成

from PIL import Image,ImageFilter


用法 XXX.py XX.jpg 100



import sys
import Image
import ImageFilter

def prepare_image(img):
    """Transform image to greyscale and blur it"""
    img = img.filter(ImageFilter.SMOOTH_MORE)
    img = img.filter(ImageFilter.SMOOTH_MORE)
    if 'L' != img.mode:
        img = img.convert('L')
    return img

def remove_noise(img, pass_factor):
    for column in range(img.size[0]):
        for line in range(img.size[1]):
            value = remove_noise_by_pixel(img, column, line, pass_factor)
            img.putpixel((column, line), value)
    return img

def remove_noise_by_pixel(img, column, line, pass_factor):
    if img.getpixel((column, line)) < pass_factor:
        return (0)
    return (255)


if __name__=="__main__":
    input_image = sys.argv[1]
    output_image = 'out_' + input_image
    pass_factor = int(sys.argv[2])

    img = Image.open(input_image)
    img = prepare_image(img)
    img = remove_noise(img, pass_factor)
    img.save(output_image)




3,识别

这里用到开源OCR库tesseract

开源的软件免费,但相对的说明文件就不足,只有自己查代码

因为验证码一般只有一行,这个

api.SetPageSegMode(tesseract.PSM_AUTO)
改成
api.SetPageSegMode(7)


import tesseract
api = tesseract.TessBaseAPI()
api.Init(".","eng",tesseract.OEM_DEFAULT)
api.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyz")
api.SetPageSegMode(tesseract.PSM_AUTO)

mImgFile = "eurotext.jpg"
mBuffer=open(mImgFile,"rb").read()
result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api)
print "result(ProcessPagesBuffer)=",result


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值