Python基于OpenCV批量生成验证码的实现方法

七月
七月
发布时间:2026-10-14 | 5人浏览过
原创

本文介绍使用Python和OpenCV库批量生成验证码的方法。通过随机生成字符、线段及背景图像,实现验证码的自动化制作。文中提供了完整代码示例,并指出因文件名重复导致生成数量略少于设定值的情况,整体效果良好。

Python OpenCV批量生成验证码实现

核心思路是利用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批量生成验证码的详细内容,更多相关技术文章请持续关注本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表