爬虫Python验证码识别入门
作者:李国宝 发布时间:2021-01-31 15:31:19
标签:爬虫,Python,验证码
目录
爬虫Python验证码识别
1、批量下载验证码图片
2、识别代码看看效果
3、折腾降噪、去干扰
爬虫Python验证码识别
前言:
二值化、普通降噪、8邻域降噪
tesseract、tesserocr、PIL
参考文献--代码地址:https://github.com/liguobao/python-verify-code-ocr
1、批量下载验证码图片
import shutil
import requests
from loguru import logger
for i in range(100):
url = 'http://xxxx/create/validate/image'
response = requests.get(url, stream=True)
with open(f'./imgs/{i}.png', 'wb') as out_file:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, out_file)
logger.info(f"download {i}.png successfully.")
del response
2、识别代码看看效果
from PIL import Image
import tesserocr
img = Image.open("./imgs/98.png")
img.show()
img_l = img.convert("L")# 灰阶图
img_l.show()
verify_code1 = tesserocr.image_to_text(img)
verify_code2 = tesserocr.image_to_text(img_l)
print(f"verify_code1:{verify_code1}")
print(f"verify_code2:{verify_code2}")
毫无疑问,无论是原图还是灰阶图,一无所有。
3、折腾降噪、去干扰
Python图片验证码降噪 - 8邻域降噪
from PIL import Image
# https://www.cnblogs.com/jhao/p/10345853.html Python图片验证码降噪 — 8邻域降噪
def noise_remove_pil(image_name, k):
"""
8邻域降噪
Args:
image_name: 图片文件命名
k: 判断阈值
Returns:
"""
def calculate_noise_count(img_obj, w, h):
"""
计算邻域非白色的个数
Args:
img_obj: img obj
w: width
h: height
Returns:
count (int)
"""
count = 0
width, height = img_obj.size
for _w_ in [w - 1, w, w + 1]:
for _h_ in [h - 1, h, h + 1]:
if _w_ > width - 1:
continue
if _h_ > height - 1:
continue
if _w_ == w and _h_ == h:
continue
if img_obj.getpixel((_w_, _h_)) < 230: # 这里因为是灰度图像,设置小于230为非白色
count += 1
return count
img = Image.open(image_name)
# 灰度
gray_img = img.convert('L')
w, h = gray_img.size
for _w in range(w):
for _h in range(h):
if _w == 0 or _h == 0:
gray_img.putpixel((_w, _h), 255)
continue
# 计算邻域非白色的个数
pixel = gray_img.getpixel((_w, _h))
if pixel == 255:
continue
if calculate_noise_count(gray_img, _w, _h) < k:
gray_img.putpixel((_w, _h), 255)
return gray_img
if __name__ == '__main__':
image = noise_remove_pil("./imgs/1.png", 4)
image.show()
看下图效果:
这样差不多了,不过还可以提升
提升新思路:
这边的干扰线是从某个点发出来的红色线条,
其实我只需要把红色的像素点都干掉,这个线条也会被去掉。
from PIL import Image
import tesserocr
img = Image.open("./imgs/98.png")
img.show()
# 尝试去掉红像素点
w, h = img.size
for _w in range(w):
for _h in range(h):
o_pixel = img.getpixel((_w, _h))
if o_pixel == (255, 0, 0):
img.putpixel((_w, _h), (255, 255, 255))
img.show()
img_l = img.convert("L")
# img_l.show()
verify_code1 = tesserocr.image_to_text(img)
verify_code2 = tesserocr.image_to_text(img_l)
print(f"verify_code1:{verify_code1}")
print(f"verify_code2:{verify_code2}")
看起来OK,上面还有零星的蓝色像素掉,也可以用同样的方法一起去掉。
甚至OCR都直接出效果了
好了,完结撒花。
不过,后面发现,有些红色线段和蓝色点,是和验证码重合的。
这个时候,如果直接填成白色,就容易把字母切开,导致识别效果变差。
当前点是红色或者蓝色,判断周围点是不是超过两个像素点是黑色。
是,填充为黑色。
否,填充成白色。
最终完整代码:
from PIL import Image
import tesserocr
from loguru import logger
class VerfyCodeOCR():
def __init__(self) -> None:
pass
def ocr(self, img):
""" 验证码OCR
Args:
img (img): imgObject/imgPath
Returns:
[string]: 识别结果
"""
img_obj = Image.open(img) if type(img) == str else img
self._remove_pil(img_obj)
verify_code = tesserocr.image_to_text(img_obj)
return verify_code.replace("\n", "").strip()
def _get_p_black_count(self, img: Image, _w: int, _h: int):
""" 获取当前位置周围像素点中黑色元素的个数
Args:
img (img): 图像信息
_w (int): w坐标
_h (int): h坐标
Returns:
int: 个数
"""
w, h = img.size
p_round_items = []
# 超过了横纵坐标
if _w == 0 or _w == w-1 or 0 == _h or _h == h-1:
return 0
p_round_items = [img.getpixel(
(_w, _h-1)), img.getpixel((_w, _h+1)), img.getpixel((_w-1, _h)), img.getpixel((_w+1, _h))]
p_black_count = 0
for p_item in p_round_items:
if p_item == (0, 0, 0):
p_black_count = p_black_count+1
return p_black_count
def _remove_pil(self, img: Image):
"""清理干扰识别的线条和噪点
Args:
img (img): 图像对象
Returns:
[img]: 被清理过的图像对象
"""
w, h = img.size
for _w in range(w):
for _h in range(h):
o_pixel = img.getpixel((_w, _h))
# 当前像素点是红色(线段) 或者 绿色(噪点)
if o_pixel == (255, 0, 0) or o_pixel == (0, 0, 255):
# 周围黑色数量大于2,则把当前像素点填成黑色;否则用白色覆盖
p_black_count = self._get_p_black_count(img, _w, _h)
if p_black_count >= 2:
img.putpixel((_w, _h), (0, 0, 0))
else:
img.putpixel((_w, _h), (255, 255, 255))
logger.info(f"_remove_pil finish.")
# img.show()
return img
if __name__ == '__main__':
verfyCodeOCR = VerfyCodeOCR()
img_path = "./imgs/51.png"
img= Image.open(img_path)
img.show()
ocr_result = verfyCodeOCR.ocr(img)
img.show()
logger.info(ocr_result)
来源:https://www.cnblogs.com/liguobao/p/15111849.html
0
投稿
猜你喜欢
- 我就废话不多说了,直接上代码吧!#Copyright (c)2017, 东北大学软件学院学生# All rightsreserved#文件名
- <% Dim aData aData = Array(3,2,4,1,6
- ini文件是windows中经常使用的配置文件,主要的格式为:[Section1]option1 : value1option2 : val
- 阅读:Chapter 3 * 的表格“Misquotations are the only quotations tha are never
- 在安装SQL Server 2000 ,安装进程自动地为“BUILTIN\Administrators&rdqu
- 介绍据官方所述,mango Cache是对Guava Cache基于go的部分实现,同时mangoCache参考了Caffeine以及go-
- 测试语法如下:powered by jb51.netexec GetRecordFromPage news,newsid,10,100000
- 本文实例讲述了JS实现淘宝支付宝网站的控制台菜单效果。分享给大家供大家参考。具体如下:这是一款支付宝网站中的控制台总菜单,可实现动画效果的显
- 在编程时你一定碰到过时间触发的事件,在VB中有timer控件,而ASP中没有,假如你要不停地查询数据库来等待一个返回结果的话,我想你一定知道
- 索引 经常要查询的语句,则给它建一个索引 表连接 select T_Oders as o join T_Customers as C on
- 一、Scrapy是什么Scrapy 是一个基于 Twisted 的异步处理框架,是纯 Python 实现的爬虫框架,其架构清晰,模块之间的耦
- Access允许您在数据库表中包含附件。通过利用微软的对象链接和嵌入(OLE)技术,您可以将照片、图表、文档及其他文件存储在您的Access
- 如下所示:def list_dict_duplicate_removal(): data_list = [{"a&qu
- Pycharm - Python 开发工具通过 agent 代理使用1、下载 Pycharm下载地址2、支持本代理包支持 2020 版本3、
- 什么是SQL 指令植入式攻击?在设计或者维护Web网站时,你也许担心它们会受到某些卑鄙用户的恶意攻击。的确,如今的Web网站开发者们针对其站
- 一、前言在本系列前面几篇文章中,我们分别介绍了 argparse 和 docopt 的主要功能和用法。它们各具特色,都能出色地完成命令行任务
- 今天我们来写一个有管理功能的留言板程序。所谓的管理功能,其实就是每条留言前有一个选择框,点中要删除的留言,或者点“删除所有留言”,就完成了批
- 本文实例讲述了Python从MP3文件获取id3的方法。分享给大家供大家参考。具体如下:def getID3(filename): &nbs
- 前言经常在 https://lichess.org/ 上观看大师们玩的国际象棋比赛。这些棋局和棋手的水平超出了我们的想象,如果想知道谁有优势
- 在代码中添加以下两行可以解决:torch.backends.cudnn.enabled = Truetorch.backends.cudnn