对较简单的验证码进行识别并返回结果
含:数字,英文
"""
1、将验证码进行二值化处理,保存到本地
2、放大验证码的尺寸,保存到本地
3、识别验证码,返回结果
"""
from PIL import Image
from PIL import ImageFile
import tesserocr
class ProcessImg:
def __init__(self):
self.filename = 'yanzhengma.png'
self.width = 200
self.height = 100
self.type = 'png'
self.i = 'in.png'
self.o = 'out.png'
def get_grey_img(self, filename):
"""
:param filename: 'yanzhengma.png'
:return: 'result.png'
"""
image = Image.open(filename)
image = image.convert('L')
threshold = 130
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1')
# show:弹窗查看,调整阈值 threshold
# image.show()
image.save('in.png')
def ResizeImage(self, filein, fileout, width, height, type):
"""
:param filein: 输入图片
:param fileout: 输出图片
:param 输出图片宽度
:param height: 输出图片高度
:param type: 输出图片类型(png, gif, jpeg...)
:return:
"""
img = Image.open(filein)
out = img.resize((width, height), Image.ANTIALIAS)
out.save(fileout, type)
def change_img_size(self, width, height, type, i, o):
ImageFile.LOAD_TRUNCATED_IMAGES = True
self.ResizeImage(i, o, width, height, type)
def get_result(self):
return tesserocr.file_to_text('out.png')
def run(self):
"""
:return: 识别结果 str
"""
self.get_grey_img(self.filename)
self.change_img_size(self.width, self.height, self.type, self.i, self.o)
return self.get_result()
if __name__ == '__main__':
start = ProcessImg()
result = start.run()