定义常量
# author: suoxd123@126.com
# 常量
NUMBER = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
LOWERCASE = ['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']
UPPERCASE = ['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']
CAPTCHA_LEN = 4
CAPTCHA_HEIGHT = 60
CAPTCHA_WIDTH = 160
CAPTCHA_COUNT = 1000
CAPTCHA_DIR = './captcha/'
生成随机字符
# author: suoxd123@126.com
# 生成随机字符
import random
def getRandomText(charset = NUMBER, length = CAPTCHA_LEN):
text = [random.choice(charset) for _ in range(length)]
return ''.join(text)
生成本地验证码
# author: suoxd123@126.com
# 生成验证码并存储到本地
import os
from captcha.image import ImageCaptcha
def createCaptcha(dataset=[NUMBER], path='./img/', height=50, width=150, len = 4, image='.png'):
if not os.path.exists(path):
os.mkdir(path)
charset = []
for a in dataset:
charset.extend(a)
captcha = ImageCaptcha(width=width, height=height)
text = getRandomText(charset)
captcha.write(text, path + text + image)# 验证码写入文件
return
# 生成1000个图片验证码
for _ in range(CAPTCHA_COUNT):
# 需要什么内容,首个参数列出来即可
# 小写字母:[LOWERCASE]
# 仅字母:[LOWERCASE, UPPERCASE]
# 数字 + 小写字母:[NUMBER, LOWERCASE]
createCaptcha([NUMBER, LOWERCASE, UPPERCASE], CAPTCHA_DIR, CAPTCHA_HEIGHT, CAPTCHA_WIDTH)
生成内存验证码
# author: suoxd123@126.com
# 生成验证码
import numpy as np
import PIL.Image as Image
def makeCaptcha(dataset=[NUMBER], height=50, width=150, len=4):
charset = []
for a in dataset:
charset.extend(a)
images, texts = [], []
captcha = ImageCaptcha(width=width, height=height)
text = getRandomText(charset)
image = np.array(Image.open(captcha.generate(text))) # 验证码写入内存
return image, text
# 生成1000个图片验证码
texts, images = [None]*CAPTCHA_COUNT,[None]*CAPTCHA_COUNT
for i in range(CAPTCHA_COUNT):
tmpImg, tmpText = makeCaptcha([NUMBER, LOWERCASE, UPPERCASE], CAPTCHA_HEIGHT, CAPTCHA_WIDTH)
images[i] = tmpImg
texts[i] = tmpText
在线绘制验证码
# 在线绘制验证码
import matplotlib.pyplot as plt
figure = plt.figure()
for i in range(30):
plt.subplot(5, 6, i+1)
plt.tight_layout()
plt.imshow(images[i])
plt.title(texts[i])
plt.xticks([])
plt.yticks([])
plt.show()
结果查看