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