生成简单验证码(可旋转)
主要思想:创建一个黑底的背景,再创建4个黑色背景的带字的图片,把4张图片粘贴上去最后在图片上加随机噪点。(提供一种生成验证码的思路,当然有更加简洁的代码利用opencv掩膜加与操作几行就能搞定,仅仅想锻炼下各位的编程能力)
import random
from PIL import ImageFont ,ImageDraw, Image
import numpy as np
import cv2 as cv
def ranchar():#随机文字
a = chr(np.random.randint(65,90))
b = chr(np.random.randint(97, 122))
c = str(np.random.randint(0, 9))
return random.choice([a,b,c])
def ranColor():#随机颜色
return (random.randint(65,255),
random.randint(65,255),
random.randint(65,255))
def ranColor2():#随机颜色
return (random.randint(188,255),
random.randint(188,255),
random.randint(188,255))
def word_size():#随机字体
return np.random.randint(100,200)
def rotate_angle():#随机旋转角度
return np.random.randint(-80,80)
def paste_image(image_backround):
for i in range(4):
image1 = Image.fromarray(np.uint8(np.random.uniform(0, 0, (400, 400, 3))))
draw=ImageDraw.Draw(image1)
draw.text((2*np.random.randint(1,40),2*np.random.randint(1,40)),ranchar(),fill=ranColor2(),font=font)
image_rotate=image1.rotate(rotate_angle())
image_backround.paste(image_rotate,(i*400,0))
return image_backround
def random_drawline(img):
for i in range(np.random.randint(3,5)):
draw=ImageDraw.Draw(img)
draw.line((np.random.randint(0,400),0,np.random.randint(500,1600),np.random.randint(0,400)),fill=ranColor2(),width=9)
return img
if __name__ == '__main__':
font = ImageFont.truetype("msyh.ttc",word_size())
image_backround = Image.fromarray(np.uint8(np.random.uniform(188, 255, (400, 1600, 3))))
image_backround=paste_image(image_backround)
image_backround2 = Image.fromarray(np.uint8(np.random.uniform(100, 255, (400, 1600, 3))))
image_backround2=random_drawline(image_backround2)
image_backround.save("a.jpg" )
image_backround2.save("b.jpg")
src1=cv.imread("a.jpg")
src2=cv.imread('b.jpg')
dst=cv.bitwise_or(src2,src1)
dst1=cv.blur(dst,(5,5))
cv.namedWindow("jieguo",cv.WINDOW_AUTOSIZE)
cv.imshow("jieguo",dst1)
cv.waitKey(0)
cv.destroyAllWindows()
结果: