想做一下验证码的图像识别,所以自己生成验证码图片来做数据集。
第一步生成随机数或者字母:
import random, string
#全部字母
string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#全部数字
string.digits
'0123456789'
#编写随机函数:
def getRandomChar():
all = string.ascii_letters + string.digits
return random.sample(all, 1)[0]
第二步生成随机颜色:
# 获取随机颜色
def getRandomColor(low, high):
return (random.randint(low, high), random.randint(low, high), random.randint(low, high))
第三步随机生成图片:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import matplotlib.pyplot as plt
def pic():
#设置图片size
width, height = 50, 50
# 创建空白画布
image = Image.new('RGB', (width, height), getRandomColor(20, 100))
# 验证码的字体
font = ImageFont.truetype('C:/Windows/fonts/stxinwei.ttf', 50)
# 创建画笔
draw = ImageDraw.Draw(image)
draw.text((10, 0), getRandomChar(), font=font, fill=getRandomColor(100,255))
return image
plt.imshow(pic())
plt.show()
第四步调整函数,生成有四个符号的验证码
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import matplotlib.pyplot as plt
def pic():
#设置图片size
width, height = 180, 60
# 创建空白画布
image = Image.new('RGB', (width, height), getRandomColor(20, 100))
# 验证码的字体
font = ImageFont.truetype('C:/Windows/fonts/stxinwei.ttf', 50)
# 创建画笔
draw = ImageDraw.Draw(image)
for i in range(0,4):
draw.text((10 + 40*i, 0), getRandomChar(), font=font, fill=getRandomColor(100,255))
return image
plt.imshow(pic())
plt.show()
第五步保存图片到本地:
name = ''
for i in range(0,4):
ch_ar = getRandomChar()
draw.text((10 + 40*i, 0),ch_ar , font=font, fill=getRandomColor(100,255))
name += ch_ar
image.save(f'{name}.png')
汇总:
import random, string
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import matplotlib.pyplot as plt
def getRandomChar():
all = string.ascii_letters + string.digits
return random.sample(all, 1)[0]
def getRandomColor(low, high):
return (random.randint(low, high), random.randint(low, high), random.randint(low, high))
def pic():
#设置图片size
width, height = 180, 60
# 创建空白画布
image = Image.new('RGB', (width, height), getRandomColor(20, 100))
# 验证码的字体
font = ImageFont.truetype('C:/Windows/fonts/stxinwei.ttf', 50)
# 创建画笔
draw = ImageDraw.Draw(image)
name = ''
for i in range(0,4):
ch_ar = getRandomChar()
draw.text((10 + 40*i, 0),ch_ar , font=font, fill=getRandomColor(100,255))
name += ch_ar
image.save(f'{name}.png')
return image,name
if __name__ == '__main__':
size = 100#设置生成多少个图片
for i in range(0, size):
key = pic()
print(key[1], 'is ok')