声明:本文章中的验证码爬取和识别仅用作试验!
1.首先就是验证码的爬取,这里我爬取的是学校oj的注册验证码。背景基本没有噪声,容易处理。
2.在获得验证码图片的二进制数据后,我们使用以下代码实现对图片的本地保存:
def save_img(content):
'''
os.getcwd()方法用于返回当前的工作目录;
md(content).hexdigest()根据图片的二进制代码产生md5码;
wb为写入二进制数据
'''
file_path = '{0}/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg')
print(file_path)
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(content)
f.close()
3.使用BytesIO对二进制文件进行封装,并用Image.open()打开。
def picture_to_string(content):
#使用BytesIO对二进制进行封装
file_like = BytesIO(content)
img = Image.open(file_like)
return img
4.图片转文字
def get_string(img):
#转化为灰度
gray = img.convert('L')
#二值化算法,阈值为140
out = get_bin_table(gray,140)
#保存处理后的图片
out.save('example','png')
#使用pytesseract.image_to_string()方法提取处理后图片的文字
word = pytesseract.image_to_string(out)
ascii_word = ''.join(c for c in word if c in string.ascii_letters or c in string.digits)
return ascii_word
def get_bin_table(img,threshold):
"""
获取灰度转二值的映射table
:param threshold:
:return:
"""
pixdata = img.load()
w,h = img.size
print(w,h)
for x in range(w):
for y in range(h):
if pixdata[x,y] < threshold:
pixdata[x,y] = 0
else:
pixdata[x,y] = 255
return img
5.效果