首先我们利用TensorFlow实现数字+字母形式的验证码,下面我们来分析一下直接生成数字类型验证码和数字+字母类型验证码的区别。
首先我们采取的验证码为四位数字类型。具体程序代码如下:
#验证码生成库
from captcha.image import ImageCaptcha #pip install captcha
import numpy as np
from PIL import Image
import random
import sys
number = ['0','1','2','3','4','5','6','7','8','9']
def random_captcha_text(char_set = number,captcha_size=4):
#验证码列表
captcha_text = []
for i in range(captcha_size):
#随机选择
c = random.choice(char_set)
#加入验证码列表
captcha_text.append(c)
return captcha_text
#生成字符对应的验证码
def gen_captcha_text_and_image():
image = ImageCaptcha()
#获得随机生成的验证码
captcha_text = random_captcha_text()
#将验证码列表转换为字符串
captcha_text = ''.join(captcha_text)
#生成验证码
captcha = image.generate(captcha_text)
image.write(captcha_text,'captcha/images/'+captcha_text + '.jpg') #写入到文件中去
num = 10000
if __name__ == '__main__':
for i in range(num):
gen_captcha_text_and_image()
sys.stdout.write('\r>> Create image %d %d' % (i+1,num))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
print('生成完毕')
生成完毕之后,我们可以在captcha/images/目录下发现已经生成了四位数字的验证码图片,当然文件数一定会少于10000,因为会存在重名覆盖。
如果要使生成的验证码图片为数字+字母类型。则需更改部分代码:
程序如下:
#验证码生成库
from captcha.image import ImageCaptcha #pip install captcha
import numpy as np
from PIL import Image
import random
import sys
number = ['0','1','2','3','4','5','6','7','8','9']
alphabet1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ALPHABET1 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
def random_captcha_text(char_set = number+alphabet1+ALPHABET1,captcha_size=4):
#验证码列表
captcha_text = []
for i in range(captcha_size):
#随机选择
c = random.choice(char_set)
#加入验证码列表
captcha_text.append(c)
return captcha_text
#生成字符对应的验证码
def gen_captcha_text_and_image():
image = ImageCaptcha()
#获得随机生成的验证码
captcha_text = random_captcha_text()
#将验证码列表转换为字符串
captcha_text = ''.join(captcha_text)
#生成验证码
captcha = image.generate(captcha_text)
image.write(captcha_text,'captcha/images/'+captcha_text + '.jpg') #写入到文件中去
num = 10000
if __name__ == '__main__':
for i in range(num):
gen_captcha_text_and_image()
sys.stdout.write('\r>> Create image %d %d' % (i+1,num))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
print('生成完毕')