captcha
captcha是用python写的生成验证码的库,它支持图片验证码和语音验证码,本次工程实训我使用的是生成图片验证码的功能。
使用方法
首先用pip安装
pip install captcha
训练数据时,我们可以选择两种方式生成我们的训练数据,一种时一次性生成多张(几万张)图片然后开始训练,一种时定义一个数据生成器,然后利用fit_generator函数(利用Python的生成器,逐个生成数据的batch并进行训练。适合于训练数据集非常大的情况,不能同时将数据载入内存中)来训练。
设置验证码格式为数字,生成一串验证码:

1 import numpy as np 2 import random 3 from captcha.image import ImageCaptcha 4 from PIL import Image 5 import matplotlib.pyplot as plt 6 7 code_char_set = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 8 9 # 字符集长度 10 code_char_set_size = len(code_char_set) 11 # 字符-数字字典(字符转数字) 12 code_char_2_number_dict = dict(zip(code_char_set, range(len(code_char_set)))) 13 # 数字-字符字典(数字转字符) 14 code_number_2_char_dict = dict(zip(range(len(code_char_set)), code_char_set)) 15 # 验证码中的字符数目 16 code_size = 4 17 18 19 # 随机产生验证码的字符 20 def random_code_text(code_size=4): # 传入验证码长度 21 code_text = [] 22 for i in range(code_size): 23 c = random.choice(code_char_set) # 随机选择字符集中的一个字符 24 code_text.append(c) # 添加到列表中 25 return code_text # 返回一个长度为4的列表 26 27 28 # 加字符列表转换为一个验证码的Image对象 29 def generate_code_image(code_size=4): 30 image = ImageCaptcha() 31 code_text = random_code_text(code_size) 32 code_text = ''.join(code_text) 33 # 将字符串转换为验证码(流) 34 captcha = image.generate(code_text) 35 # 保存验证码图片 36 image.write(code_text, './' + code_text + '.jpg') 37 38 # 将验证码转换为图片的形式 39 code_image = Image.open(captcha) 40 code_image = np.array(code_image) 41 42 return code_text, code_image 43 44 45 if __name__ == '__main__': 46 text, image = generate_code_image(4) 47 ax = plt.figure() 48 ax.text(0.1, 0.9, text, ha='center', va='center') 49 plt.imshow(image) 50 plt.show()