1.找到可识别素材,保存本地,方便python识别验证码实验
先找到一些素材库,利用python发送网络请求,并保存文件
注意到的一些细节是保存文件时,需以二进制形式读写,并使用函数flush,强制清空缓冲区。
import requests url = "************" s = requests.Session() #print s.get(url).content for i in range(100): f = open(str(i) + '.bmp', 'wb') f.write(s.get(url).content) f.flush() f.close()
这是我抓的一部分图片素材
2.利用素材进行图片的处理
将彩色验证码图片转为灰度图,并将灰度图转为二值图。
二值化是图像分割的一种常用方法。在二值化图象的时候把大于某个临界灰度值的像素灰度设为灰度极大值,把小于这个值的像素灰度设为灰度极小值,从而实现二值化(一般设置为0-1)。根据阈值选取的不同,二值化的算法分为固定阈值和自适应阈值,这里选用比较简单的固定阈值。
把像素点大于阈值的设置,1,小于阈值的设置为0。生成一张查找表,再调用point()进行映射。
import cv2 import Image def get_bin_table(threshold=140): table = [] for i in range(256): if i < threshold: table.append(0) else: table.append(1) return table #img = cv2.imread("1.bmp", cv2.IMREAD_GRAYSCALE) #cv2.imwrite("101.bmp", img) #img = cv2.imread("101.bmp") #Grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #ret, thresh = cv2.threshold(Grayimg, 12, 255,cv2.THRESH_BINARY) #cv2.imwrite('1001.bmp', thresh) image = Image.open('1.bmp') imary = image.convert('L') table = get_bin_table() out = imary.point(table, '1') #out.show() img_array = out.load() print out.size for i in range(out.size[0]): for j in range(out.size[1]): print str(img_array[i, j]), print "\n"处理为二值图片后,并把像素值进行打印。
略微缩小些,可以看到大体的数字在里面。
3.安装pytesseract第三方库并进行简单二维码识别。
pytesseract第三方库具体用法请自行百度
下面是一些安装依赖
pip install opencv-python //安装pytesseract //各种依赖,各种pip install apt-cache search tesseract apt-get install tesseract-ocr sudo pip install pytesseract sudo pip install pillow
可识别验证码图片放上来一张:
import pytesseract from PIL import Image for i in range(1, 101): filename = str(i) + '.bmp' image = Image.open(filename) code = pytesseract.image_to_string(image) #print filename + 'is null' #code = pytesser.image_file_to_string(filename) #print filename + ' the twice ocr ' + code print filename + ' ' + code #print "the twice is" + pytesseract.image_file_to_string(filename)
另该模块之可识别一些简单的验证码图片,干扰性稍强的图片该库无法识别,请注意,需要进行降噪处理,降噪需要算法支持。