from captcha.image import ImageCaptcha
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
num = ['0','1','2','3','4','5','6','7','8','9']
alph = [chr(65+i) for i in range(26)]
ALPH = [chr(97+i) for i in range(26)]
#得到含有4个字母或数字的验证码
def random_captcha_text(size=4 ,charset=num+alph+ALPH):
capta_text = []
for i in range(size):
capta_text.append(choice(charset))
return capta_text
def gen_captcha_image():
image = ImageCaptcha()
#生成验证码字母的组合
captcha_text = random_captcha_text()
captcha_text = ''.join(captcha_text)
catpchaInfo = image.generate(captcha_text)
captcha_image = Image.open(catpchaInfo)
captcha_image = np.array(captcha_image)
return captcha_text,captcha_image
if __name__ == '__main__':
text,image = gen_captcha_image()
f = plt.figure()
ax = f.add_subplot(111)
ax.text(0.1,0.9,text,ha='center',va='center')
plt.imshow(image)
plt.show()
运行结果