请选择 进入手机版 | 继续访问电脑版

Hello Mat

 找回密码
 立即注册
查看: 5721|回复: 0

生成验证码

[复制链接]

1278

主题

1504

帖子

90

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22549
发表于 2021-5-22 18:16:49 | 显示全部楼层 |阅读模式
验证码:
  1. # coding:utf-8
  2. import random
  3. import os
  4. from PIL import Image, ImageDraw, ImageFont

  5. char_set = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  6. image_size = (128, 32)

  7. """
  8. 基本:
  9. 1 图片size
  10. 2 字符个数
  11. 3 字符区域(重叠、等分)
  12. 4 字符位置(固定、随机)
  13. 5 字符size(所占区域大小的百分比)
  14. 6 字符fonts
  15. 7 字符 type (数字、字母、汉字、数学符号)
  16. 8 字符颜色
  17. 9 背景颜色
  18. 高级:
  19. 10 字符旋转
  20. 11 字符扭曲
  21. 12 噪音(点、线段、圈)
  22. """


  23. def randRGB():
  24.     return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)


  25. def cha_draw(cha, text_color, font, rotate, size_cha):
  26.     im = Image.new(mode='RGBA', size=(size_cha * 2, size_cha * 2))
  27.     drawer = ImageDraw.Draw(im)
  28.     drawer.text(xy=(0, 0), text=cha, fill=text_color, font=font)  # text 内容,fill 颜色, font 字体(包括大小)
  29.     if rotate:
  30.         max_angle = 40  # to be tuned
  31.         angle = random.randint(-max_angle, max_angle)
  32.         im = im.rotate(angle, Image.BILINEAR, expand=1)
  33.     im = im.crop(im.getbbox())
  34.     return im


  35. def choice_cha(chas):
  36.     x = random.randint(0, len(chas))
  37.     return chas[x - 1]


  38. def captcha_draw(size_im, nb_cha, set_cha, fonts=None, overlap=0.0,
  39.                  rd_bg_color=False, rd_text_color=False, rd_text_pos=False, rd_text_size=False,
  40.                  rotate=False, noise=None, dir_path='', img_num=0, img_now=0):
  41.     """
  42.         overlap: 字符之间区域可重叠百分比, 重叠效果和图片宽度字符宽度有关
  43.         字体大小 目前长宽认为一致!!!
  44.         所有字大小一致
  45.         扭曲暂未实现
  46.         noise 可选:point, line , circle
  47.         fonts 中分中文和英文字体
  48.         label全保存在label.txt 中,文件第i行对应"i.jpg"的图片标签,i从1开始
  49.     """
  50.     rate_cha = 0.8  # rate to be tuned
  51.     width_im, height_im = size_im
  52.     width_cha = int(width_im / max(nb_cha - overlap, 3))  # 字符区域宽度
  53. #    height_cha = height_im * 1.2  # 字符区域高度
  54.     height_cha = height_im * 0.8  # 字符区域高度
  55.     bg_color = 'white'
  56.     text_color = 'black'
  57.     derx = 0
  58.     dery = 0

  59.     if rd_text_size:
  60.         rate_cha = random.uniform(rate_cha - 0.1, rate_cha + 0.1)  # to be tuned
  61.     size_cha = int(rate_cha * min(width_cha, height_cha) * 2.0)  # 字符大小

  62.     if rd_bg_color:
  63.         bg_color = randRGB()
  64.     im = Image.new(mode='RGB', size=size_im, color=bg_color)  # color 背景颜色,size 图片大小

  65.     drawer = ImageDraw.Draw(im)
  66.     contents = []
  67.     for i in range(nb_cha):
  68.         if rd_text_color:
  69.             text_color = randRGB()
  70.         if rd_text_pos:
  71.             derx = random.randint(0, max(width_cha - size_cha - 5, 0))
  72.             dery = random.randint(0, max(height_cha - size_cha - 5, 0))

  73.         cha = random.choice(set_cha)
  74.         font = ImageFont.truetype(fonts['eng'], size_cha)
  75.         contents.append(cha)
  76.         im_cha = cha_draw(cha, text_color, font, rotate, size_cha)
  77.         im.paste(im_cha, (int(max(i - overlap, 0) * width_cha) + derx + 2, dery + 3), im_cha)  # 字符左上角位置
  78.    
  79.     if 'point' in noise:
  80.         nb_point = 20
  81.         color_point = randRGB()
  82.         for i in range(nb_point):
  83.             x = random.randint(0, width_im)
  84.             y = random.randint(0, height_im)
  85.             drawer.point(xy=(x, y), fill=color_point)
  86.     if 'line' in noise:
  87.         nb_line = 3
  88.         for i in range(nb_line):
  89.             color_line = randRGB()
  90.             sx = random.randint(0, width_im)
  91.             sy = random.randint(0, height_im)
  92.             ex = random.randint(0, width_im)
  93.             ey = random.randint(0, height_im)
  94.             drawer.line(xy=(sx, sy, ex, ey), fill=color_line)
  95.     if 'circle' in noise:
  96.         nb_circle = 20
  97.         color_circle = randRGB()
  98.         for i in range(nb_circle):
  99.             sx = random.randint(0, width_im - 10)
  100.             sy = random.randint(0, height_im - 10)
  101.             temp = random.randint(1, 5)
  102.             ex = sx + temp
  103.             ey = sy + temp
  104.             drawer.arc((sx, sy, ex, ey), 0, 360, fill=color_circle)

  105.     if os.path.exists(dir_path) == False:  # 如果文件夹不存在,则创建对应的文件夹
  106.         os.mkdir(dir_path)

  107.     img_name = str(img_now) + '_' + ''.join(contents) + '.jpg'
  108.     img_path = os.path.join(dir_path, img_name)
  109.     print (img_path, str(img_now) + '/' + str(img_num))
  110.     im.save(img_path)


  111. def captcha_generator(ctc = False):
  112.     size_im = image_size#(176, 25)
  113.     set_chas = [char_set]
  114.     if ctc:
  115.         nb_chas = [4,5,6,7,8]
  116.     else:
  117.         nb_chas = [4]
  118.     nb_image = 500
  119.     font_dir = './fonts/'
  120.     rd_bg_color = False
  121.    
  122.     overlaps = [0.0, 0.1, 0.2]
  123.     noises = [[], ['point'], ['line'], ['line', 'point'], ['circle']]
  124.    
  125.     rd_text_poss = [False]      #[True, False]
  126.     rd_text_sizes = [False]     #[True, False]
  127.     rd_text_colors = [True, False]  # false 代表字体颜色全一致,但都是黑色
  128.     rotates = [False]       #[True, False]
  129.    
  130.    
  131.     font_paths = []
  132.     for dirpath, dirnames, filenames in os.walk(font_dir):
  133.         for filename in filenames:
  134.             filepath = dirpath + os.sep + filename
  135.             font_paths.append({'eng': filepath})

  136.         for i in range(nb_image):
  137.             overlap = random.choice(overlaps)
  138.             rd_text_pos = random.choice(rd_text_poss)
  139.             rd_text_size = random.choice(rd_text_sizes)
  140.             rd_text_color = random.choice(rd_text_colors)
  141.             set_cha = random.choice(set_chas)
  142.             noise = random.choice(noises)
  143.             rotate = random.choice(rotates)
  144.             nb_cha = random.choice(nb_chas)
  145. #            font_path = random.choice(font_paths)
  146.             font_path = font_paths[0]
  147.             if ctc:
  148.                 dir_name = 'ctc'
  149.             else:
  150.                 dir_name = 'cnn'
  151.         
  152.             dir_path = './img_data/' + dir_name + '/'
  153.             captcha_draw(size_im=size_im, nb_cha=nb_cha, set_cha=set_cha,
  154.                          overlap=overlap, rd_text_pos=rd_text_pos, rd_text_size=rd_text_size,
  155.                          rd_text_color=rd_text_color, rd_bg_color=rd_bg_color, noise=noise,
  156.                          rotate=rotate, dir_path=dir_path, fonts=font_path, img_num=nb_image, img_now=i)


  157. def test():
  158.     print("test begining ------------------")
  159. #    size_im = (100, 30)
  160.     size_im = (128, 32)
  161.     set_chas = [
  162.         "0123456789",
  163.         "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  164.         "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  165.         "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  166.         "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  167.     ]
  168.     overlaps = [0.8, 0.4, 0.6, 0.8, 0.4, 0.6, 0.5, 0.0, 0.2]
  169.     rd_text_poss = [False, True]
  170.     rd_text_sizes = [False, True]
  171.     rd_text_colors = [False, True]  # false 代表字体颜色全一致,但都是黑色
  172.     rd_bg_color = False
  173.    
  174.     noises = [['point'], ['line'], ['line', 'point']]
  175.     rotates = [False]
  176.     nb_chas = [4]
  177.     nb_image = 100#1000 * 100
  178. #    font_dir = '/usr/share/fonts/truetype/ubuntu-font-family'
  179. #    font_dir = 'C:/Windows/Fonts/'
  180.     font_dir = './fonts/'
  181.     font_paths = []
  182.     num_pic = 0
  183.     dir_folder = 0

  184.     try:
  185.         for dirpath, dirnames, filenames in os.walk(font_dir):
  186.             print("test begining ---------0---------")
  187.             for filename in filenames:
  188.                 filepath = dirpath + os.sep + filename
  189.                 font_paths.append({'eng': filepath})
  190.                 print("font-------",filepath)

  191.             for i in range(nb_image):
  192.                 print("test begining -----1-------------")
  193.                 num_pic += 1
  194.                 overlap = random.choice(overlaps)
  195.                 rd_text_pos = random.choice(rd_text_poss)
  196.                 rd_text_size = random.choice(rd_text_sizes)
  197.                 rd_text_color = random.choice(rd_text_colors)
  198.                 set_cha = random.choice(set_chas)
  199.                 noise = random.choice(noises)
  200.                 rotate = random.choice(rotates)
  201.                 nb_cha = random.choice(nb_chas)
  202. #                font_path = random.choice(font_paths)
  203.                 font_path = font_paths[0]
  204.                 if num_pic % 1001 == 0:
  205.                     dir_folder += 1
  206.                 dir_name = 'train_data'
  207.                 dir_path = './img_data/' + dir_name + '/'
  208.                 captcha_draw(size_im=size_im, nb_cha=nb_cha, set_cha=set_cha,
  209.                              overlap=overlap, rd_text_pos=rd_text_pos, rd_text_size=rd_text_size,
  210.                              rd_text_color=rd_text_color, rd_bg_color=rd_bg_color, noise=noise,
  211.                              rotate=rotate, dir_path=dir_path, fonts=font_path, img_num=nb_image, img_now=i)
  212.     except Exception:
  213.         print ("io Exception--- ")


  214. if __name__ == "__main__":
  215.     #test()
  216.      captcha_generator(True)
复制代码



算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2024-3-29 08:58 , Processed in 0.203624 second(s), 21 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表