好的,我们可以在验证码的背景中添加一些干扰点,并对数字和符号进行拉伸和倾斜处理。以下是更新后的代码示例:
import random
from PIL import Image, ImageDraw, ImageFont
# 设置图像大小
width, height = 200, 100
# 随机生成两个数字和一个运算符
num1 = random.randint(0, 1000)
num2 = random.randint(0, 1000)
operators = ['+', '-', '×', '÷']
operator = random.choice(operators)
# 生成验证码字符串
captcha_text = f"{num1} {operator} {num2}"
# 创建图像
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
# 添加干扰点
for _ in range(100): # 生成100个干扰点
x = random.randint(0, width)
y = random.randint(0, height)
draw.point((x, y), fill=(200, 200, 200)) # 灰色干扰点
# 设置字体(可根据需要修改字体路径)
font = ImageFont.load_default()
# 计算文本大小并随机拉伸和倾斜
text_width, text_height = draw.textsize(captcha_text, font=font)
text_x = (width - text_width) // 2
text_y = (height - text_height) // 2
# 随机倾斜和拉伸
angle = random.uniform(-15, 15) # 随机倾斜角度
scale = random.uniform(0.8, 1.2) # 随机拉伸比例
# 创建一个新的图像用于绘制变换后的文本
text_image = Image.new('RGB', (text_width, text_height), (255, 255, 255))
text_draw = ImageDraw.Draw(text_image)
# 绘制文本
text_draw.text((0, 0), captcha_text, fill=(139, 69, 19), font=font)
# 旋转和缩放文本
text_image = text_image.rotate(angle, expand=1)
text_image = text_image.resize((int(text_width * scale), int(text_height * scale)))
# 将变换后的文本粘贴到背景图像上
text_x = (width - text_image.width) // 2
text_y = (height - text_image.height) // 2
image.paste(text_image, (text_x, text_y), text_image)
# 保存图像
image.save('captcha_with_noise.png')
# 显示图像
image.show()
代码说明:
- 干扰点:在背景中随机生成100个灰色干扰点。
- 随机倾斜和拉伸:
- 使用
random.uniform生成一个随机倾斜角度(-15到15度)。 - 生成一个随机拉伸比例(0.8到1.2)。
- 文本绘制:首先在一个新的图像上绘制文本,然后对其进行旋转和缩放,最后将变换后的文本粘贴回原始图像中。
这样生成的验证码将更加复杂和难以识别。你可以根据需要调整干扰点的数量和颜色。