python识别验证码图片实例详解


Posted in Python onFebruary 17, 2020

在编写自动化测试用例的时候,每次登录都需要输入验证码,后来想把让python自己识别图片里的验证码,不需要自己手动登陆,所以查了一下识别功能怎么实现,做一下笔记。

首选导入一些用到的库,re、Image、pytesseract、selenium、time

import re # 用于正则
from PIL import Image # 用于打开图片和对图片处理
import pytesseract # 用于图片转文字
from selenium import webdriver # 用于打开网站
import time # 代码运行停顿

首先需要获取验证码图片,才能进一步识别。

创建类,定义webdriver和find_element_by_selector方法,用来打开网页和定位验证码图片的元素

class VerificationCode:
 def __init__(self):
  self.driver = webdriver.Firefox()
  self.find_element = self.driver.find_element_by_css_selector

然后打开浏览器截取验证码图片

def get_pictures(self):
  self.driver.get('http://123.255.123.3') # 打开登陆页面
  self.driver.save_screenshot('pictures.png') # 全屏截图
  page_snap_obj = Image.open('pictures.png')
  img = self.find_element('#pic') # 验证码元素位置
  time.sleep(1)
  location = img.location
  size = img.size # 获取验证码的大小参数
  left = location['x']
  top = location['y']
  right = left + size['width']
  bottom = top + size['height']
  image_obj = page_snap_obj.crop((left, top, right, bottom)) # 按照验证码的长宽,切割验证码
  image_obj.show() # 打开切割后的完整验证码
  self.driver.close() # 处理完验证码后关闭浏览器
  return image_obj

未处理前的验证码图片如下:

python识别验证码图片实例详解

未处理的验证码图片,对于python来说识别率较低,仔细看可以发现图片里有很对五颜六色扰乱识别的点,非常影响识别率。

下面对获取的验证码进行处理。

首先用convert把图片转成黑白色。设置threshold阈值,超过阈值的为黑色

def processing_image(self):
  image_obj = self.get_pictures() # 获取验证码
  img = image_obj.convert("L") # 转灰度
  pixdata = img.load()
  w, h = img.size
  threshold = 160 # 该阈值不适合所有验证码,具体阈值请根据验证码情况设置
  # 遍历所有像素,大于阈值的为黑色
  for y in range(h):
   for x in range(w):
    if pixdata[x, y] < threshold:
     pixdata[x, y] = 0
    else:
     pixdata[x, y] = 255
  return img

经过灰度处理后的图片

python识别验证码图片实例详解

然后删除一些扰乱识别的像素点。

def delete_spot(self):
  images = self.processing_image()
  data = images.getdata()
  w, h = images.size
  black_point = 0
  for x in range(1, w - 1):
   for y in range(1, h - 1):
    mid_pixel = data[w * y + x] # 中央像素点像素值
    if mid_pixel < 50: # 找出上下左右四个方向像素点像素值
     top_pixel = data[w * (y - 1) + x]
     left_pixel = data[w * y + (x - 1)]
     down_pixel = data[w * (y + 1) + x]
     right_pixel = data[w * y + (x + 1)]
     # 判断上下左右的黑色像素点总个数
     if top_pixel < 10:
      black_point += 1
     if left_pixel < 10:
      black_point += 1
     if down_pixel < 10:
      black_point += 1
     if right_pixel < 10:
      black_point += 1
     if black_point < 1:
      images.putpixel((x, y), 255)
     black_point = 0
  # images.show()
  return images

经过去除噪点处理后的图片

python识别验证码图片实例详解

最后把处理后的图片转成文字。

先设置pytesseract的路径,因为默认路径是错的,然后转换图片为文字,由于个别图片中识别会出现处理遗漏,会被识别成空格或则点或则分号什么的,所以增加了一个去除验证码中特殊字符的处理。

def image_str(self):
  image = self.delete_spot()
  pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" # 设置pyteseract路径
  result = pytesseract.image_to_string(image) # 图片转文字
  resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result) # 去除识别出来的特殊字符
  result_four = resultj[0:4] # 只获取前4个字符
  # print(resultj) # 打印识别的验证码
  return result_four

完整代码如下:

import re # 用于正则
from PIL import Image # 用于打开图片和对图片处理
import pytesseract # 用于图片转文字
from selenium import webdriver # 用于打开网站
import time # 代码运行停顿
 
 
class VerificationCode:
 def __init__(self):
  self.driver = webdriver.Firefox()
  self.find_element = self.driver.find_element_by_css_selector
 
 def get_pictures(self):
  self.driver.get('http://123.255.123.3') # 打开登陆页面
  self.driver.save_screenshot('pictures.png') # 全屏截图
  page_snap_obj = Image.open('pictures.png')
  img = self.find_element('#pic') # 验证码元素位置
  time.sleep(1)
  location = img.location
  size = img.size # 获取验证码的大小参数
  left = location['x']
  top = location['y']
  right = left + size['width']
  bottom = top + size['height']
  image_obj = page_snap_obj.crop((left, top, right, bottom)) # 按照验证码的长宽,切割验证码
  image_obj.show() # 打开切割后的完整验证码
  self.driver.close() # 处理完验证码后关闭浏览器
  return image_obj
 
 def processing_image(self):
  image_obj = self.get_pictures() # 获取验证码
  img = image_obj.convert("L") # 转灰度
  pixdata = img.load()
  w, h = img.size
  threshold = 160
  # 遍历所有像素,大于阈值的为黑色
  for y in range(h):
   for x in range(w):
    if pixdata[x, y] < threshold:
     pixdata[x, y] = 0
    else:
     pixdata[x, y] = 255
  return img
 
 def delete_spot(self):
  images = self.processing_image()
  data = images.getdata()
  w, h = images.size
  black_point = 0
  for x in range(1, w - 1):
   for y in range(1, h - 1):
    mid_pixel = data[w * y + x] # 中央像素点像素值
    if mid_pixel < 50: # 找出上下左右四个方向像素点像素值
     top_pixel = data[w * (y - 1) + x]
     left_pixel = data[w * y + (x - 1)]
     down_pixel = data[w * (y + 1) + x]
     right_pixel = data[w * y + (x + 1)]
     # 判断上下左右的黑色像素点总个数
     if top_pixel < 10:
      black_point += 1
     if left_pixel < 10:
      black_point += 1
     if down_pixel < 10:
      black_point += 1
     if right_pixel < 10:
      black_point += 1
     if black_point < 1:
      images.putpixel((x, y), 255)
     black_point = 0
  # images.show()
  return images
 
 def image_str(self):
  image = self.delete_spot()
  pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" # 设置pyteseract路径
  result = pytesseract.image_to_string(image) # 图片转文字
  resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result) # 去除识别出来的特殊字符
  result_four = resultj[0:4] # 只获取前4个字符
  # print(resultj) # 打印识别的验证码
  return result_four
 
 
 
if __name__ == '__main__':
 a = VerificationCode()
 a.image_str()

更多关于python识别验证码图片方法请查看下面的相关链接

Python 相关文章推荐
Python版的文曲星猜数字游戏代码
Sep 02 Python
Python 字符串大小写转换的简单实例
Jan 21 Python
Python 统计字数的思路详解
May 08 Python
Python使用numpy模块创建数组操作示例
Jun 20 Python
对python中数据集划分函数StratifiedShuffleSplit的使用详解
Dec 11 Python
python flask几分钟实现web服务的例子
Jul 26 Python
python破解bilibili滑动验证码登录功能
Sep 11 Python
在Python中画图(基于Jupyter notebook的魔法函数)
Oct 28 Python
linux 下python多线程递归复制文件夹及文件夹中的文件
Jan 02 Python
opencv中图像叠加/图像融合/按位操作的实现
Apr 01 Python
Python应用实现处理excel数据过程解析
Jun 19 Python
python爬虫筛选工作实例讲解
Nov 23 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
Feb 17 #Python
Matplotlib使用字符串代替变量绘制散点图的方法
Feb 17 #Python
关于tf.TFRecordReader()函数的用法解析
Feb 17 #Python
将数据集制作成VOC数据集格式的实例
Feb 17 #Python
将labelme格式数据转化为标准的coco数据集格式方式
Feb 17 #Python
开启Django博客的RSS功能的实现方法
Feb 17 #Python
Python3打包exe代码2种方法实例解析
Feb 17 #Python
You might like
用php制作简单分页(从数据库读取记录)的方法详解
2013/05/04 PHP
ioncube_loader_win_5.2.dll的错误解决方法
2015/01/04 PHP
php通过Chianz.com获取IP地址与地区的方法
2015/01/14 PHP
laravel 框架结合关联查询 when()用法分析
2019/11/22 PHP
基于jQuery判断两个元素是否有重叠部分的代码
2012/07/25 Javascript
javascript获取网页中指定节点的父节点、子节点的方法小结
2013/04/24 Javascript
浅析LigerUi开发中谨慎载入common.css文件
2013/07/09 Javascript
jQuery实现的调整表格行tr上下顺序
2016/01/10 Javascript
Javascript的表单验证长度
2016/03/16 Javascript
搭建vue开发环境
2018/07/19 Javascript
最适应的vue.js的form提交涉及多种插件【推荐】
2018/08/27 Javascript
Vue props 单向数据流的实现
2018/11/06 Javascript
关于vue里页面的缓存详解
2019/11/04 Javascript
Vue父组件向子组件传值以及data和props的区别详解
2020/03/02 Javascript
解决vue-cli输入命令vue ui没效果的问题
2020/11/17 Javascript
原生js实现弹窗消息动画
2020/11/20 Javascript
python openvc 裁剪、剪切图片 提取图片的行和列
2019/09/19 Python
浅谈python中频繁的print到底能浪费多长时间
2020/02/21 Python
使用Python+selenium实现第一个自动化测试脚本
2020/03/17 Python
Python爬虫爬取杭州24时温度并展示操作示例
2020/03/27 Python
Python Map 函数的使用
2020/08/28 Python
Python中三维坐标空间绘制的实现
2020/09/22 Python
CSS3绘制超炫的上下起伏波动进度加载动画
2016/04/21 HTML / CSS
html5 datalist标签使用示例(自动完成组件)
2014/05/04 HTML / CSS
详解使用双缓存解决Canvas clearRect引起的闪屏问题
2019/04/29 HTML / CSS
Flesh Beauty官网:露华浓集团旗下彩妆品牌
2021/02/15 全球购物
外贸学院会计专业应届生求职信
2013/11/14 职场文书
数学与统计学院学生个人职业生涯规划书
2014/02/10 职场文书
我的大学生活演讲稿
2014/04/25 职场文书
三好学生先进事迹材料
2014/08/28 职场文书
机关干部三严三实心得体会
2014/10/13 职场文书
六年级小学生评语
2014/12/26 职场文书
2015年服务员个人工作总结
2015/05/27 职场文书
失恋33天观后感
2015/06/11 职场文书
Golang 空map和未初始化map的注意事项说明
2021/04/29 Golang
Python基础之元组与文件知识总结
2021/05/19 Python