当前位置:首页 » 编程语言 » python识别验证码

python识别验证码

发布时间: 2022-09-28 15:48:37

A. 如何利用python做简单的验证码识别

1摘要

验证码是目前互联网上非常常见也是非常重要的一个事物,充当着很多系统的防火墙功能,但是随时OCR技术的发展,验证码暴露出来的安全问题也越来越严峻。本文介绍了一套字符验证码识别的完整流程,对于验证码安全和OCR识别技术都有一定的借鉴意义。

然后经过了一年的时间,笔者又研究和get到了一种更强大的基于CNN卷积神经网络的直接端到端的验证识别技术(文章不是我的,然后我把源码整理了下,介绍和源码在这里面):

基于python语言的tensorflow的‘端到端’的字符型验证码识别源码整理(github源码分享)

2关键词

关键词:安全,字符图片,验证码识别,OCR,Python,SVM,PIL

3免责声明

本文研究所用素材来自于某旧Web框架的网站完全对外公开的公共图片资源。

本文只做了该网站对外公开的公共图片资源进行了爬取,并未越权做任何多余操作。

本文在书写相关报告的时候已经隐去漏洞网站的身份信息。

本文作者已经通知网站相关人员此系统漏洞,并积极向新系统转移。

本报告的主要目的也仅是用于OCR交流学习和引起大家对验证安全的警觉。

4引言

关于验证码的非技术部分的介绍,可以参考以前写的一篇科普类的文章:

互联网安全防火墙(1)--网络验证码的科普

里面对验证码的种类,使用场景,作用,主要的识别技术等等进行了讲解,然而并没有涉及到任何技术内容。本章内容则作为它的技术补充来给出相应的识别的解决方案,让读者对验证码的功能及安全性问题有更深刻的认识。

5基本工具

要达到本文的目的,只需要简单的编程知识即可,因为现在的机器学习领域的蓬勃发展,已经有很多封装好的开源解决方案来进行机器学习。普通程序员已经不需要了解复杂的数学原理,即可以实现对这些工具的应用了。

主要开发环境:

  • python3.5

  • python SDK版本

  • PIL

  • 图片处理库

  • libsvm

  • 开源的svm机器学习库

  • 关于环境的安装,不是本文的重点,故略去。

    6基本流程

    一般情况下,对于字符型验证码的识别流程如下:

  • 准备原始图片素材

  • 图片预处理

  • 图片字符切割

  • 图片尺寸归一化

  • 图片字符标记

  • 字符图片特征提取

  • 生成特征和标记对应的训练数据集

  • 训练特征标记数据生成识别模型

  • 使用识别模型预测新的未知图片集

  • 达到根据“图片”就能返回识别正确的字符集的目标

  • 7素材准备

    7.1素材选择

    由于本文是以初级的学习研究目的为主,要求“有代表性,但又不会太难”,所以就直接在网上找个比较有代表性的简单的字符型验证码(感觉像在找漏洞一样)。

    最后在一个比较旧的网站(估计是几十年前的网站框架)找到了这个验证码图片。

    原始图:

  • def get_feature(img): """

  • 获取指定图片的特征值,

  • 1. 按照每排的像素点,高度为10,则有10个维度,然后为6列,总共16个维度

  • :param img_path:

  • :return:一个维度为10(高度)的列表 """


  • width, height = img.size


  • pixel_cnt_list = []

  • height = 10 for y in range(height):

  • pix_cnt_x = 0 for x in range(width): if img.getpixel((x, y)) == 0: # 黑色点

  • pix_cnt_x += 1


  • pixel_cnt_list.append(pix_cnt_x) for x in range(width):

  • pix_cnt_y = 0 for y in range(height): if img.getpixel((x, y)) == 0: # 黑色点

  • pix_cnt_y += 1


  • pixel_cnt_list.append(pix_cnt_y) return pixel_cnt_list

  • 然后就将图片素材特征化,按照libSVM指定的格式生成一组带特征值和标记值的向量文

B. 使用Python进行验证码识别案例无法验证通过,SOS

是不是PIL需要的依赖图像支持没有下?
试试这个
sudo apt-get install zlib1g-dev
sudo apt-get install libfreetype6-dev
sudo apt-get build-dep python-imaging
能安装的都安上

C. python怎样调用第三方平台识别验证码

一、pytesseract介绍

1、pytesseract说明

pytesseract最新版本0.1.6,网址:h

Python-tesseract is a wrapper for google's Tesseract-OCR
( ht-ocr/ ). It is also useful as a
stand-alone invocation script to tesseract, as it can read all image types
supported by the Python Imaging Library, including jpeg, png, gif, bmp, tiff,
and others, whereas tesseract-ocr by default only supports tiff and bmp.
Additionally, if used as a script, Python-tesseract will print the recognized
text in stead of writing it to a file. Support for confidence estimates and
bounding box data is planned for future releases.

翻译一下大意:

a、Python-tesseract是一个基于google's Tesseract-OCR的独立封装包;

b、Python-tesseract功能是识别图片文件中文字,并作为返回参数返回识别结果;

c、Python-tesseract默认支持tiff、bmp格式图片,只有在安装PIL之后,才能支持jpeg、gif、png等其他图片格式;

2、pytesseract安装

INSTALLATION:

Prerequisites:
* Python-tesseract requires python 2.5 or later or python 3.
* You will need the Python Imaging Library (PIL). Under Debian/Ubuntu, this is
the package "python-imaging" or "python3-imaging" for python3.
* Install google tesseract-ocr from hsseract-ocr/ .
You must be able to invoke the tesseract command as "tesseract". If this
isn't the case, for example because tesseract isn't in your PATH, you will
have to change the "tesseract_cmd" variable at the top of 'tesseract.py'.
Under Debian/Ubuntu you can use the package "tesseract-ocr".

Installing via pip:
See the [pytesseract package page](hi/pytesseract)
```
$> sudo pip install pytesseract

翻译一下:

a、Python-tesseract支持python2.5及更高版本;

b、Python-tesseract需要安装PIL(Python Imaging Library) ,来支持更多的图片格式;

c、Python-tesseract需要安装tesseract-ocr安装包,具体参看上一篇博文。

综上,Pytesseract原理:

1、上一篇博文中提到,执行命令行 tesseract.exe 1.png output -l eng ,可以识别1.png中文字,并把识别结果输出到output.txt中;

2、Pytesseract对上述过程进行了二次封装,自动调用tesseract.exe,并读取output.txt文件的内容,作为函数的返回值进行返回。

二、pytesseract使用

USAGE:
```
> try:
> import Image
> except ImportError:
> from PIL import Image
> import pytesseract
> print(pytesseract.image_to_string(Image.open('test.png')))
> print(pytesseract.image_to_string(Image.open('test-european.jpg'),))

可以看到:

1、核心代码就是image_to_string函数,该函数还支持-l eng 参数,支持-psm 参数。

用法:
image_to_string(Image.open('test.png'),lang="eng" config="-psm 7")

2、pytesseract里调用了image,所以才需要PIL,其实tesseract.exe本身是支持jpeg、png等图片格式的。

实例代码,识别某公共网站的验证码(大家千万别干坏事啊,思虑再三,最后还是隐掉网站域名,大家去找别的网站试试吧……):

View Code

D. 如何利用Python 做验证码识别

用python加“验证码”为关键词在里搜一下,可以找到很多关于验证码识别的文章。我大体看了一下,主要方法有几类:一类是通过对图片进行处理,然后利用字库特征匹配的方法,一类是图片处理后建立字符对应字典,还有一类是直接利用ocr模块进行识别。不管是用什么方法,都需要首先对图片进行处理,于是试着对下面的验证码进行分析。
一、图片处理
这个验证码中主要的影响因素是中间的曲线,首先考虑去掉图片中的曲线。考虑了两种算法
第一种是首先取到曲线头的位置,即x=0时,黑点的位置。然后向后移动x的取值,观察每个x下黑点的位置,判断前后两个相邻黑点之间的距离,如果距离在一定范围内,可以基本判断该点是曲线上的点,最后将曲线上的点全部绘成白色。试了一下这种方法,结果得到的图片效果很一般,曲线不能完全去除,而且容量将字符的线条去除。
第二种考虑用单位面积内点的密度来进行计算。于是首先计算单位面积内点的个数,将单位面积内点个数少于某一指定数的面积去除,剩余的部分基本上就是验证码字符的部分。本例中,为了便于操作,取了5*5做为单位范围,并调整单位面积内点的标准密度为11。处理后的效果:
二、字符验证
这里我使用的方法是利用pytesser进行ocr识别,但由于这类验证码字符的不规则性,使得验证结果的准确性并不是很高。具体哪位大牛,有什么好的办法,希望能给指点一下。
三、准备工作与代码实例
1、PIL、pytesser、tesseract
(1)安装PIL:下载地址:http:// www. pythonware. com/procts/pil/(2)pytesser:下载地址:http :/ /code. google. com/p/pytesser/,下载解压后直接放在代码相同的文件夹下,即可使用。
(3)Tesseract OCR engine下载:http: / / code.google. com/p/tesseract-ocr/,下载后解压,找到tessdata文件夹,用其替换掉pytesser解压后的tessdata文件夹即可。
2、具体代码
复制代码
#encoding=utf-8
###利用点的密度计算
import Image,ImageEnhance,ImageFilter,ImageDrawimport sys
from pytesser import *
#计算范围内点的个数
def numpoint(im):
w,h = im.size
data = list( im.getdata() )
mumpoint=0
for x in range(w):
for y in range(h):
if data[ y*w + x ] !=255:#255是白色
mumpoint+=1
return mumpoint
#计算5*5范围内点的密度
def pointmi(im):
w,h = im.size
p=[]
for y in range(0,h,5):
for x in range(0,w,5):
box = (x,y, x+5,y+5)
im1=im.crop(box)
a=numpoint(im1)
if a<11:##如果5*5范围内小于11个点,那么将该部分全部换为白色。
for i in range(x,x+5):
for j in range(y,y+5):
im.putpixel((i,j), 255)
im.save(r'img.jpg')
def ocrend():##识别
image_name = "img.jpg"
im = Image.open(image_name)
im = im.filter(ImageFilter.MedianFilter())enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save("1.tif")
print image_file_to_string('1.tif')
if __name__=='__main__':
image_name = "1.png"
im = Image.open(image_name)
im = im.filter(ImageFilter.DETAIL)
im = im.filter(ImageFilter.MedianFilter())enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
##a=remove_point(im)
pointmi(im)
ocrend()

E. Python有什么好的库可以识别验证码

要安装pytesseract库,必须先安装其依赖的PIL及tesseract-ocr,其中PIL为图像处理库,而后面的tesseract-ocr则为google的ocr识别引擎。

pytesseract安装
直接使用pip install pytesseract安装即可,或者使用easy_install pytesseract

Python验证码识别代码:

import pytesseract
from PIL import Image
image = Image.open('vcode.png')
vcode = pytesseract.image_to_string(image)
print (vcode)

F. python tesserocr识别普通验证码成功后打印结果为空

和threshold=127这个有关系,变更这个数值就能看出来了,比如调成200

G. 如何用Python+人工识别处理知乎的倒立汉字验证码

这给Python爬虫的模拟登录带来了一定的难度,目前网络上的相关资料针对的都是普通的“英文+数字”验证码,针对“倒立汉字”验证码的文章较少。而且大家普遍采用的是requests库。经过几天的研究,我采用urllib.request实现了模拟登陆知乎,现将代码分享如下:

[python] view plain
# 登录知乎,通过保存验证图片方式
import urllib.request
import urllib.parse
import time
import http.cookiejar

webUrl = "l"#不能写因为不支持重定向

webheader = {
# 'Accept': 'text/html, application/xhtml+xml, */*',
# 'Accept-Language': 'zh-CN',
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36',
# 'User-Agent': 'Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
# 'DNT': '1',
# 'Connection': 'Keep-Alive'
}

postData = {
'email': '在这里写你的账号',
'captcha_type': 'cn',
'password': '在这里写你的密码',
'_xsrf': '',
'captcha': ''
}
localStorePath = "写你想保存的验证码图片的地址"

if __name__ == '__main__':
#声明一个CookieJar对象实例来保存cookie
cookie = http.cookiejar.CookieJar()
#创建opener
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)#建立opener对象,并添加头信息
urllib.request.install_opener(opener)

captcha_url = '?r=%d&type=login&lang=cn' % (time.time() * 1000)
# captcha_url = '/captcha.gif?r=%d&type=login' % (time.time() * 1000)#这样获得的是“字母+数字验证码”

#这个获取验证码图片的方法是不行的!
# urllib.request.urlretrieve(captcha_url, localStorePath + 'myCaptcha.gif')

#用urlopen函数保存验证图片
req = urllib.request.Request(url=captcha_url,headers=webheader)
content = urllib.request.urlopen(req)
# content = opener.open(req)
captcha_name = 'D:/Python学习/crawler_learning/知乎登录专题研究/知乎验证码图片/myNewCaptcha.gif'
content = content.read()
with open(captcha_name, 'wb') as f:
f.write(content)

postData['captcha'] = input('请输入验证码')
# postData['_xsrf'] = get_xsrf()
postData['_xsrf'] = ''
print(postData['_xsrf'])

#用urlopen函数传送数据给服务器实现登录
postData_encoded = urllib.parse.urlencode(postData).encode('utf-8')
req = urllib.request.Request(url=webUrl,data=postData_encoded,headers=webheader)
webPage = urllib.request.urlopen(req)
# webPage = opener.open(req)
data = webPage.read().decode('utf-8')

print(data)
with open("D:/知乎服务器反馈的内容.txt",mode='w',encoding='utf-8') as dataFile:
dataFile.write(data)

几点思考:
1、首先需要明确如何获得验证码图片的地址,利用Fiddler抓包获得的典型的验证码图片的地址如下:

这个“r”代表的是什么含义呢?经过查看知乎上的js代码可以确定,这个r指的是毫秒级的时间戳。
2、以验证码图片地址cn为例,不同时间访问同一个验证码图片地址,得到的验证码图片是不同的,那么知乎服务器是如何知道你获取的是那张验证码呢?
我认为是通过sessionID,换句话说,知乎把某个验证码图片给了你,同时知乎记录下了你的sessionID和这个验证码的“正确答案”,这样将来你输入验证码给知乎后,知乎就能判断你输入的验证码是否正确了。
由于sessionID保存在cookie之中,所以Python模拟登陆的代码必须使用cookie。
3、获取验证码图片的时候,我用的是content =urllib.request.urlopen (req)函数,经过我的验证,用
urllib.request.urlretrieve函数是不行的,因为urlopen函数可以传递headers参数,而这一个参数必须有。

4、获得了倒立汉字图片以后,如何确定要传递给知乎的captcha是什么呢?经过Fiddler抓包,
传递的参数类似于这样:
{"img_size":[200,44],"input_points":[[43.44,22.44],[115.72,22.44]]}
经过分析和试验确定:200指的是图片长度,44指的是图片高度,后面的input_points指的是打在倒立汉字上的点的坐标。由于每次出现7个汉字,这7个汉字的坐标是固定的,我全部进行捕获:
{"img_size":[200,44],"input_points":[[12.95,14.969999999999998],[36.1,16.009999999999998],[57.16,24.44],[84.52,19.17],[108.72,28.64],[132.95,24.44],[151.89,23.380000000000002]]}
然后,问题就简单了:将图片保存在本地之后,打开图片,确定哪几个汉字倒立,比如说第2个和第6个,那就在上面选取出2和6的坐标输入即可,即
{"img_size":[200,44],"input_points":[[36.1,16.009999999999998],[132.95,24.44]]}。
5、小窍门:以验证码图片地址

H. 如何用Python+人工识别处理知乎的倒立汉字验证码

#登录知乎,通过保存验证图片方式
importurllib.request
importurllib.parse
importtime
importhttp.cookiejar

webUrl="https://www.hu.com/login/email"#不能写https://www.hu.com/#signin因为不支持重定向

webheader={
#'Accept':'text/html,application/xhtml+xml,*/*',
#'Accept-Language':'zh-CN',
#'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64;Trident/7.0;rv:11.0)likeGecko',
'User-Agent':'Mozilla/5.0(Linux;Android6.0;Nexus5Build/MRA58N)AppleWebKit/537.36(KHTML,likeGecko)Chrome/56.0.2924.87MobileSafari/537.36',
#'User-Agent':'Mozilla/5.0(iPod;U;CPUiPhoneOS4_3_3likeMacOSX;en-us)AppleWebKit/533.17.9(KHTML,likeGecko)Version/5.0.2Mobile/8J2Safari/6533.18.5',
#'DNT':'1',
#'Connection':'Keep-Alive'
}

postData={
'email':'在这里写你的账号',
'captcha_type':'cn',
'password':'在这里写你的密码',
'_xsrf':'',
'captcha':''
}
localStorePath="写你想保存的验证码图片的地址"

if__name__=='__main__':
#声明一个CookieJar对象实例来保存cookie
cookie=http.cookiejar.CookieJar()
#创建opener
handler=urllib.request.HTTPCookieProcessor(cookie)
opener=urllib.request.build_opener(handler)#建立opener对象,并添加头信息
urllib.request.install_opener(opener)

captcha_url='https://www.hu.com/captcha.gif?r=%d&type=login&lang=cn'%(time.time()*1000)
#captcha_url='http://www.hu.com/captcha.gif?r=%d&type=login'%(time.time()*1000)#这样获得的是“字母+数字验证码”

#这个获取验证码图片的方法是不行的!
#urllib.request.urlretrieve(captcha_url,localStorePath+'myCaptcha.gif')

#用urlopen函数保存验证图片
req=urllib.request.Request(url=captcha_url,headers=webheader)
content=urllib.request.urlopen(req)
#content=opener.open(req)
captcha_name='D:/Python学习/crawler_learning/知乎登录专题研究/知乎验证码图片/myNewCaptcha.gif'
content=content.read()
withopen(captcha_name,'wb')asf:
f.write(content)

postData['captcha']=input('请输入验证码')
#postData['_xsrf']=get_xsrf()
postData['_xsrf']=''
print(postData['_xsrf'])

#用urlopen函数传送数据给服务器实现登录
postData_encoded=urllib.parse.urlencode(postData).encode('utf-8')
req=urllib.request.Request(url=webUrl,data=postData_encoded,headers=webheader)
webPage=urllib.request.urlopen(req)
#webPage=opener.open(req)
data=webPage.read().decode('utf-8')

print(data)
withopen("D:/知乎服务器反馈的内容.txt",mode='w',encoding='utf-8')asdataFile:
dataFile.write(data)

热点内容
cad字体在那个文件夹 发布:2024-05-05 17:08:20 浏览:329
什么时候用编译器 发布:2024-05-05 17:08:20 浏览:764
应急救援脚本 发布:2024-05-05 17:08:17 浏览:336
我的世界搭建无正版验证服务器 发布:2024-05-05 17:03:48 浏览:817
我的世界服务器地址宝可梦 发布:2024-05-05 17:00:16 浏览:254
dede企业源码 发布:2024-05-05 16:57:53 浏览:786
如何查看java版本 发布:2024-05-05 16:45:05 浏览:494
转子绕组电动机控制柜如何配置 发布:2024-05-05 16:45:04 浏览:917
搭建游戏要多大服务器 发布:2024-05-05 16:44:16 浏览:346
云服务器ecs网站 发布:2024-05-05 16:35:55 浏览:563