python 验证码识别示例(一) 某个网站验证码识别
某个招聘网站的验证码识别,过程如下
一: 原始验证码:
二: 首先对验证码进行分析,该验证码的数字颜色有变化,这个就是识别这个验证码遇到的比较难的问题,解决方法是使用PIL 中的 getpixel 方法进行变色处理,统一把非黑色的像素点变成黑色
变色后的图片
三: 通过观察,发现该验证码有折线,需要对图片进行降噪处理。
降噪后的图片
四:识别:
这里只是简单的使用 pytesseract 模块进行识别
识别结果如下:
总共十一个验证码,识别出来了9个,综合识别率是百分之八十。
总结:验证码识别只是简单调用了一下Python的第三方库,本验证码的识别难点如何给带颜色的数字变色。
下面是代码:
二值化变色:
#-*-coding:utf-8-*- from PIL import Image def test(path): img=Image.open(path) w,h=img.size for x in range(w): for y in range(h): r,g,b=img.getpixel((x,y)) if 190<=r<=255 and 170<=g<=255 and 0<=b<=140: img.putpixel((x,y),(0,0,0)) if 0<=r<=90 and 210<=g<=255 and 0<=b<=90: img.putpixel((x,y),(0,0,0)) img=img.convert('L').point([0]*150+[1]*(256-150),'1') return img for i in range(1,13): path = str(i) + '.jpg' im = test(path) path = path.replace('jpg','png') im.save(path)
二:降噪
#-*-coding:utf-8-*- # coding:utf-8 import sys, os from PIL import Image, ImageDraw # 二值数组 t2val = {} def twoValue(image, G): for y in xrange(0, image.size[1]): for x in xrange(0, image.size[0]): g = image.getpixel((x, y)) if g > G: t2val[(x, y)] = 1 else: t2val[(x, y)] = 0 # 根据一个点A的RGB值,与周围的8个点的RBG值比较,设定一个值N(0 <N <8),当A的RGB值与周围8个点的RGB相等数小于N时,此点为噪点 # G: Integer 图像二值化阀值 # N: Integer 降噪率 0 <N <8 # Z: Integer 降噪次数 # 输出 # 0:降噪成功 # 1:降噪失败 def clearNoise(image, N, Z): for i in xrange(0, Z): t2val[(0, 0)] = 1 t2val[(image.size[0] - 1, image.size[1] - 1)] = 1 for x in xrange(1, image.size[0] - 1): for y in xrange(1, image.size[1] - 1): nearDots = 0 L = t2val[(x, y)] if L == t2val[(x - 1, y - 1)]: nearDots += 1 if L == t2val[(x - 1, y)]: nearDots += 1 if L == t2val[(x - 1, y + 1)]: nearDots += 1 if L == t2val[(x, y - 1)]: nearDots += 1 if L == t2val[(x, y + 1)]: nearDots += 1 if L == t2val[(x + 1, y - 1)]: nearDots += 1 if L == t2val[(x + 1, y)]: nearDots += 1 if L == t2val[(x + 1, y + 1)]: nearDots += 1 if nearDots < N: t2val[(x, y)] = 1 def saveImage(filename, size): image = Image.new("1", size) draw = ImageDraw.Draw(image) for x in xrange(0, size[0]): for y in xrange(0, size[1]): draw.point((x, y), t2val[(x, y)]) image.save(filename) for i in range(1,12): path = str(i) + ".png" image = Image.open(path).convert("L") twoValue(image, 100) clearNoise(image, 3, 2) path1 = str(i) + ".jpeg" saveImage(path1, image.size)
三:识别
#-*-coding:utf-8-*- from PIL import Image import pytesseract def recognize_captcha(img_path): im = Image.open(img_path) # threshold = 140 # table = [] # for i in range(256): # if i < threshold: # table.append(0) # else: # table.append(1) # # out = im.point(table, '1') num = pytesseract.image_to_string(im) return num if __name__ == '__main__': for i in range(1, 12): img_path = str(i) + ".jpeg" res = recognize_captcha(img_path) strs = res.split("\n") if len(strs) >=1: print (strs[0])
如果觉得对您有帮助,麻烦您点一下推荐,谢谢!
好记忆不如烂笔头
好记忆不如烂笔头