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