两种方法进行图片验证码的制作和识别

方法一:通过PIL、pytesseract模块进行验证码的制作和识别

步骤1:利用PIL进行验证码的制作,并保存到本地
步骤2:利用pytesseract进行验证码图片的识别

#创建一张验证码、保存到本地并进行识别
import random
from PIL import Image,ImageFont,ImageDraw
# import ImageFont

def rng_char():
    return chr(random.randint(65,90))
def rng_color():
    return (random.randint(64,255),random.randint(64,255),random.randint(64,255),random.randint(64,255))

width=60*4
height=60
rng_char()
image=Image.new('RGB',(width,height),(0,0,0))
# image.show()

font=ImageFont.truetype("arialuni.ttf",36) #注意:运行文件当前目录下应有相应字体文件,否则会报错
draw=ImageDraw.Draw(image)

for i in range(4):
    draw.text((60*i+10,10),rng_char(),font=font,fill=rng_color())   
image.save('验证码图片.jpg', 'jpeg');
print("图片保存成功。")
image.show()
#验证码识别
from PIL import Image
import pytesseract
 
imageObject=Image.open('验证码图片.jpg')
print (imageObject)
print (pytesseract.image_to_string(imageObject))
生成的识别码(每次运行,生成的代码都不一样,因为是使用随机生成的数字和字母):

在这里插入图片描述

识别结果:

在这里插入图片描述

注意:运行文件当前目录下应有相应字体文件,否则会报错,这里附上字体下载地址

方法二:通过连接第三方软件自动识别(利用api接口)(亲测有用,真香﹏)

#验证码识别(可运行)(通过连接第三方软件自动识别)
import requests
from hashlib import md5

class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }
    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()
    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()
if __name__ == '__main__':
    chaojiying = Chaojiying_Client('账号名', '密码', '96001')    #用户中心>>软件ID 生成一个替换 96001
    im = open('gg.png', 'rb').read()                #本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    print(chaojiying.PostPic(im, 1902))                #1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()

注意:使用此请先到软件官网注册账号,将主函数中账号和密码进行替换。

欢迎访问我的主页

不要白嫖,加个关注,点个赞再走吧!

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45104240/article/details/105751307
今日推荐