python基于opencv批量生成验证码的示例

作者:奈何缘浅wyj 时间:2022-04-07 22:42:07 

基本思路是使用opencv来把随机生成的字符,和随机生成的线段,放到一个随机生成的图像中去。

虽然没有加复杂的形态学处理,但是目前看起来效果还不错

尝试生成1000张图片,但是最后只有998张,因为有有重复的,被覆盖掉了。

代码如下:


import cv2
import numpy as np
line_num = 10
pic_num = 1000
path = "./imgs/"
def randcolor():        
   return (np.random.randint(0,255),np.random.randint(0,255),np.random.randint(0,255))

def randchar():
   return chr(np.random.randint(65,90))

def randpos(x_start,x_end,y_start,y_end):
   return (np.random.randint(x_start,x_end),
           np.random.randint(y_start,y_end))

img_heigth = 60
img_width = 240
for i in range(pic_num):
   img_name = ""
   #生成一个随机矩阵,randint(low[, high, size, dtype])
   img = np.random.randint(100,200,(img_heigth,img_width, 3), np.uint8)
   #显示图像
   #cv2.imshow("ranImg",img)

x_pos = 0
   y_pos = 25
   for i in range(4):
       char = randchar()
       img_name += char
       cv2.putText(img,char,
                   (np.random.randint(x_pos,x_pos + 50),np.random.randint(y_pos,y_pos + 35)),
                   cv2.FONT_HERSHEY_SIMPLEX,
                   1.5,
                   randcolor(),
                   2,
                   cv2.LINE_AA)
       x_pos += 45

#cv2.imshow("res",img)

#添加线段
   for i in range(line_num):
       img = cv2.line(img,
                      randpos(0,img_width,0,img_heigth),
                      randpos(0,img_width,0,img_heigth),
                       randcolor(),
                       np.random.randint(1,2))

#cv2.imshow("line",img)
   cv2.imwrite(path + img_name + ".jpg",img)
   #cv2.waitKey(0)                  
   #cv2.destroyAllWindows()

结果:

python基于opencv批量生成验证码的示例

来源:https://juejin.cn/post/6955740180783300615

标签:python,验证码,opencv
0
投稿

猜你喜欢

  • 使用Python解析JSON数据的基本方法

    2021-07-03 13:54:21
  • Python实现二叉树前序、中序、后序及层次遍历示例代码

    2023-12-02 00:36:40
  • Python列表排序 list.sort方法和内置函数sorted用法

    2022-01-18 01:01:47
  • js:校验IPv6地址的正则表达式

    2023-06-30 23:21:33
  • php用header函数实现301跳转代码实例

    2023-10-08 11:29:59
  • Python面向对象实现方法总结

    2022-03-11 08:50:41
  • Python中的lambda和apply用法及说明

    2023-08-12 14:56:46
  • Pytest框架 conftest.py文件的使用详解

    2023-06-20 08:16:52
  • python3实现无权最短路径的方法

    2023-07-11 23:26:40
  • pandas的qcut()方法详解

    2022-07-23 03:36:21
  • 能否用显示/隐藏层来控制FLASH播放与停止

    2008-10-27 14:08:00
  • Python光学仿真学习衍射算法初步理解

    2021-01-07 13:54:46
  • MySQL命令终端有beep声

    2009-02-26 15:27:00
  • adodb.stream对象的方法/属性

    2008-06-07 08:14:00
  • 如何在Django中使用聚合的实现示例

    2021-08-02 10:32:30
  • Python正则表达中re模块的使用

    2023-10-11 03:38:22
  • python基础之并发编程(二)

    2023-01-16 03:10:37
  • Python要如何实现列表排序的几种方法

    2022-02-01 16:23:07
  • asp防止盗链HTTP_REFERER判断代码

    2010-03-12 10:41:00
  • 在IE8中继续使用滤镜及IE8的一些CSS扩展属性

    2009-02-21 11:18:00
  • asp之家 网络编程 m.aspxhome.com