使用Python生成和识别验证码可以通过以下步骤进行:
生成验证码
1. 导入所需库:
from PIL import Image, ImageDraw, ImageFont
import random
2. 定义生成验证码的函数:
def generate_code(length=4):
characters = string.ascii_letters + string.digits 包含大小写字母和数字
return ''.join(random.choice(characters) for _ in range(length))
3. 生成并显示验证码图像:
def generate_image(code):
width, height = 120, 50
bg_color = (255, 255, 255)
image = Image.new('RGB', (width, height), bg_color)
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial.ttf', 36)
text_width, text_height = draw.textsize(code, font=font)
x = (width - text_width) / 2
y = (height - text_height) / 2
draw.text((x, y), code, font=font, fill=(0, 0, 0))
return image
4. 保存或显示图像:
保存图像
image.save('captcha.png')
显示图像
image.show()
识别验证码
1. 安装OCR库(如Tesseract OCR):
pip install pytesseract
2. 使用OCR库识别验证码内容:
import pytesseract
def recognize_code(image_path):
img = Image.open(image_path)
code = pytesseract.image_to_string(img)
return code.strip()
整合使用
你可以将生成和识别验证码的步骤整合到一起,例如:
生成验证码图像
code = generate_code()
image = generate_image(code)
保存图像
image.save('captcha.png')
识别验证码
recognized_code = recognize_code('captcha.png')
print(f'Recognized Code: {recognized_code}')
以上代码展示了如何使用Python和Pillow库生成验证码图像,并使用Tesseract OCR库识别图像中的文字内容。请确保Tesseract OCR已正确安装并配置在你的系统上