// 转载请注明出处 鲲鹏数据 http://www.site-digger.com
陕西移动网厅:http://www.sn.10086.cn/
验证码生成链接:https://sn.ac.10086.cn/SSO/servlet/CreateImage
验证码示例:
该验证码较为简单:内容为四位纯数字(0-9),单个字符宽度固定,字符垂直位置固定,背景有很少的杂色。
识别方案:
1)提取特征库。
下载足够多的验证码图片(至少包含0-9所有数字)。截取每个数字(8×20像素矩阵)单独存储作为特征库。
实现方法如下(用到了Python的PIL库):
view plaincopy to clipboardprint?
import Image
def make_lib():
img = Image.open('code.jpg')
gray_img = img.convert('1')
gray_img.save('gray.jpg')
width, height = gray_img.size
# find each number
w = 0
while w < width:
column = []
for h in range(height):
column.append(gray_img.getpixel((w, h)))
# begining of a number
if sum(column)/height < 245:
box = (w, 0, w+8, 20)
region = gray_img.crop(box)
region.save('%s.jpg' % w)
w = w + 10
else:
w = w + 1
注:img.convert('1')作用是将彩色图二值化(只有0和255两种像素值)。
原理?
按列扫描,依次找到每个数字的起始位置,截取宽度为8像素,高度为20像素的区域保存。
如何识别字符的开始位置?
测试发现,列像素之合小于245的是有数字的部分。
最终建立如下特征库:
2) 匹配方案。
按列扫描,依次找到每个数字的起始位置,获取宽度为8像素,高度为20像素的矩阵A。
拿矩阵A一次跟特征库矩阵进行对比,以差值数(详见下面Captcha类中的_cmpmatrix方法)最小的特征字符为匹配字符。
下面给出我们实现的Captcha类。
view plaincopy to clipboardprint?
# coding: utf-8
# captcha.py
# http://www.site-digger.com
# hello@site-digger.com
# Identify captcha on http://www.sn.10086.cn/
import Image
class Captcha:
def __init__(self):
self.imglib = {}
self._loadlib()
def _loadlib(self):
"""Load characteristic image lib"""
import os
if not os.path.exists('imglib'):
print 'Can not find imglib dir.'
return
for i in range(10):
self.imglib[i] = []
img = Image.open('imglib/%d.jpg' % i).convert('1')
width, height = img.size
for w in range(width):
# store all pixels in a column
column = []
for h in range(height):
column.append(img.getpixel((w, h)))
self.imglib[i].append(column)
def _cmpmatrix(self, listA, listB):
"""Return the count of difference between two list"""
if len(listA) != len(listB): return
num = 0
for i, column in enumerate(listA):
if len(column) != len(listB[i]): return
for j, pixel in enumerate(column):
if pixel != listB[i][j]:
num += 1
return num
def _whichnum(self, piexls_matrix):
"""Identify single number"""
minnum = None
index = 0
for i in range(10):
ret = self._cmpmatrix(self.imglib.get(i, []), piexls_matrix)
if ret!= None:
if minnum == None or minnum > ret:
minnum = ret
index = i
if minnum != None:
return str(index)
else:
return '?'
def identify(self, filepath=None, fileobj=None):
"""Identify captcha"""
if filepath:
img = Image.open(filepath)
elif fileobj:
img = Image.open(fileobj)
else:
print 'Invalid input.'
return
img = img.convert('1')
width, height = img.size
w = 0
number = ''
while w < width:
column = []
for h in range(height):
column.append(img.getpixel((w, h)))
# begining of a number
if sum(column)/height < 245:
piexls_matrix = []
for i in range(8):
piexls_column = []
for j in range(20):
piexls_column.append(img.getpixel((w + i, j)))
piexls_matrix.append(piexls_column)
number += self._whichnum(piexls_matrix)
w = w + 10
else:
w = w + 1
return number
if __name__ == '__main__':
"""Test performance of Captcha Class"""
captcha = Captcha()
try:
import urllib2
response = urllib2.urlopen('https://sn.ac.10086.cn/SSO/servlet/CreateImage')
open('code.jpg', 'wb').write(response.read())
Image.open('code.jpg').show()
print captcha.identify('code.jpg')
except Exception, e:
print 'Download captcha fail.', e
测试用例说明: 动态下载陕西移动网厅的验证码,首先显示,然后调用Captcha类对其进行识别、打印。效果如下图所示。
特别说明:该文章为鲲鹏数据原创文章 ,你除了可以发表评论外,还可以转载到你的网站或博客,但是请保留源地址,谢谢!!(尊重他人劳动,你我共同努力)