#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 25 19:06:46 2018
@author: zlg
"""
from captcha.image import ImageCaptcha#验证码生成框架
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image#图像处理标准库
import random
number = ['0','1','2','3','4','5','6','7','8','9']
alphabet = ['a','b','c','d','e','f','g']
ALPHABT = ['A','B','C','D','E','F','G']
#验证码中的字符
def random_captcha_text(char_set=number+alphabet+ALPHABT,captcha_size=8):
captcha_text = []
for i in range(captcha_size):
c = random.choice(char_set)
captcha_text.append(c)#连接元素
return captcha_text
#生成验证码
def gen_capthcha_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_text+'.jpg')
#先生成后保存,参数1是内容,参数二是图片保存名称,三是图片格式
captcha_image = Image.open(captcha)
captcha_image = np.array(captcha_image)#将图片数据保存为矩阵
return captcha_text,captcha_image
if __name__ == '__main__':
text,image = gen_capthcha_text_and_image()
f = plt.figure()
ax = f.add_subplot(212)#参数212的意思是:将画布分割成2行1列,图像画在从左到右从上到下的第2块,
ax.text(0.1,0.1,text,ha='center',va='center',transform=ax.transAxes)
plt.imshow(image)#参数为矩阵
plt.show()
http://blog.topspeedsnail.com/archives/10858