gen_sample_by_captcha.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: UTF-8 -*-
  2. """
  3. 使用captcha lib生成验证码(前提:pip3 install captcha)
  4. """
  5. from captcha.image import ImageCaptcha
  6. import os
  7. import random
  8. import time
  9. import json
  10. from log_ware import LogWare
  11. logger = LogWare().get_logger()
  12. def gen_special_img(text, file_path, width, height):
  13. # 生成img文件
  14. generator = ImageCaptcha(width=width, height=height) # 指定大小
  15. img = generator.generate_image(text) # 生成图片
  16. img.save(file_path) # 保存图片
  17. def gen_ima_by_batch(root_dir, image_suffix, characters, count, char_count, width, height):
  18. # 判断文件夹是否存在
  19. if not os.path.exists(root_dir):
  20. os.makedirs(root_dir)
  21. for index, i in enumerate(range(count)):
  22. text = ""
  23. for j in range(char_count):
  24. text += random.choice(characters)
  25. timec = str(time.time()).replace(".", "")
  26. p = os.path.join(root_dir, "{}_{}.{}".format(text, timec, image_suffix))
  27. gen_special_img(text, p, width, height)
  28. logger.debug("Generate captcha image => %d", index + 1)
  29. def main():
  30. with open("conf/captcha_config.json", "r") as f:
  31. config = json.load(f)
  32. # 配置参数
  33. root_dir = config["root_dir"] # 图片储存路径
  34. image_suffix = config["image_suffix"] # 图片储存后缀
  35. characters = config["characters"] # 图片上显示的字符集 # characters = "0123456789abcdefghijklmnopqrstuvwxyz"
  36. count = config["count"] # 生成多少张样本
  37. char_count = config["char_count"] # 图片上的字符数量
  38. # 设置图片高度和宽度
  39. width = config["width"]
  40. height = config["height"]
  41. gen_ima_by_batch(root_dir, image_suffix, characters, count, char_count, width, height)
  42. if __name__ == '__main__':
  43. main()