pytesser 是谷歌开源的一个项目,可以用来进行图片中文字的识别
这里我们将使用它来进行简单的验证码识别。 代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'admin'
from pytesser import *
flag = 140
table = []
for i in range(256):
if i < flag:
table.append(0)
else:
table.append(1)
# 由于都是数字如果有字母的 采用该表进行修正,将相近的字母和数值作为映射
rep = {'O': '0',
'I': '1',
'L': '1',
'Z': '2',
'S': '8',
'Q': '0'}
class AuthCode(object):
def __init__(self, img_name):
self.img = img_name
def tran_to_str(self):
# 打开图片
im = Image.open(self.img)
# 图片转化成灰度图像
img_ry = im.convert('L')
# 保存灰度图像
img_ry.save('g'+self.img)
# 二值化将图像噪点去掉
out = img_ry.point(table, '1')
# 保存去掉噪点之后的图像
out.save('b'+self.img)
# 识别
text = image_to_string(out)
# 识别出来的字符进行处理
text = text.strip()
text = text.upper()
for r in rep:
text = text.replace(r, rep[r])
# out.save(text+'.jpg')
print text
return text
if __name__ == '__main__':
i = AuthCode('r2.jpg')
i.tran_to_str()
具体流程说明:
- 将图片验证码下载至本地,验证码大概如下
2 将代码转为灰度 图像
img_ry = im.convert('L')
这里采用RBG转化到HSI彩色空间,采用L分量
此时灰度图像看起来是这样的
3 再次我们将图像中的噪点去掉:
我们把大于阈值threshold的像素置为1,其他的置为0。对此,先生成一张查找表,映射过程让库函数帮我们做。
flag = 140
table = []
for i in range(256):
if i < flag:
table.append(0)
else:
table.append(1)
此时图像看起来是这样的
最后将图像保存为文本
text = image_to_string(out)
输出结果