最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

爬蟲Python驗(yàn)證碼識別入門

 更新時(shí)間:2021年08月27日 17:01:00   作者:李國寶  
這篇文章主要介紹了爬蟲Python驗(yàn)證碼識別,屬于入門級別的介紹,剛接觸爬蟲的朋友可以參考如下

爬蟲Python驗(yàn)證碼識別

前言:

二值化、普通降噪、8鄰域降噪
tesseract、tesserocr、PIL
參考文獻(xiàn)--代碼地址:https://github.com/liguobao/python-verify-code-ocr

 1、批量下載驗(yàn)證碼圖片

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圖片驗(yàn)證碼降噪 - 8鄰域降噪

from PIL import Image
# https://www.cnblogs.com/jhao/p/10345853.html Python圖片驗(yàn)證碼降噪 — 8鄰域降噪

 
def noise_remove_pil(image_name, k):
    """
    8鄰域降噪
    Args:
        image_name: 圖片文件命名
        k: 判斷閾值
    Returns:
    """

    def calculate_noise_count(img_obj, w, h):
        """
        計(jì)算鄰域非白色的個(gè)數(shù)
        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:  # 這里因?yàn)槭腔叶葓D像,設(shè)置小于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
            # 計(jì)算鄰域非白色的個(gè)數(shù)
            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()
 

看下圖效果:

這樣差不多了,不過還可以提升

提升新思路:

這邊的干擾線是從某個(gè)點(diǎn)發(fā)出來的紅色線條,

其實(shí)我只需要把紅色的像素點(diǎn)都干掉,這個(gè)線條也會(huì)被去掉。

from PIL import Image
import tesserocr
img = Image.open("./imgs/98.png")
img.show()

# 嘗試去掉紅像素點(diǎn)
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,上面還有零星的藍(lán)色像素掉,也可以用同樣的方法一起去掉。

甚至OCR都直接出效果了
好了,完結(jié)撒花。
不過,后面發(fā)現(xiàn),有些紅色線段和藍(lán)色點(diǎn),是和驗(yàn)證碼重合的。
這個(gè)時(shí)候,如果直接填成白色,就容易把字母切開,導(dǎo)致識別效果變差。
當(dāng)前點(diǎn)是紅色或者藍(lán)色,判斷周圍點(diǎn)是不是超過兩個(gè)像素點(diǎn)是黑色。
是,填充為黑色。
否,填充成白色。

最終完整代碼:

from PIL import Image
import tesserocr
from loguru import logger


class VerfyCodeOCR():
    def __init__(self) -> None:
        pass

    def ocr(self, img):
        """ 驗(yàn)證碼OCR

        Args:
            img (img): imgObject/imgPath

        Returns:
            [string]: 識別結(jié)果
        """
        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):
        """ 獲取當(dāng)前位置周圍像素點(diǎn)中黑色元素的個(gè)數(shù)

        Args:
            img (img): 圖像信息
            _w (int): w坐標(biāo)
            _h (int): h坐標(biāo)

        Returns:
            int: 個(gè)數(shù)
        """
        w, h = img.size
        p_round_items = []
        # 超過了橫縱坐標(biāo)
        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):
        """清理干擾識別的線條和噪點(diǎn)

        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))
                # 當(dāng)前像素點(diǎn)是紅色(線段) 或者 綠色(噪點(diǎn))
                if o_pixel == (255, 0, 0) or o_pixel == (0, 0, 255):
                    # 周圍黑色數(shù)量大于2,則把當(dāng)前像素點(diǎn)填成黑色;否則用白色覆蓋
                    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)


到此這篇關(guān)于爬蟲Python驗(yàn)證碼識別入門的文章就介紹到這了,更多相關(guān)Python驗(yàn)證碼識別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 對Python中畫圖時(shí)候的線類型詳解

    對Python中畫圖時(shí)候的線類型詳解

    今天小編就為大家分享一篇對Python中畫圖時(shí)候的線類型詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 用python處理圖片之打開\顯示\保存圖像的方法

    用python處理圖片之打開\顯示\保存圖像的方法

    本篇文章主要介紹了用python處理圖片之打開\顯示\保存圖像的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-05-05
  • mac系統(tǒng)下Redis安裝和使用步驟詳解

    mac系統(tǒng)下Redis安裝和使用步驟詳解

    這篇文章主要介紹了mac下Redis安裝和使用步驟詳解,并將python如何操作Redis做了簡單介紹,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • python爬蟲selenium模塊詳解

    python爬蟲selenium模塊詳解

    這篇文章主要介紹了python爬蟲selenium模塊詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Python Django安裝配置模板系統(tǒng)及使用實(shí)戰(zhàn)全面詳解

    Python Django安裝配置模板系統(tǒng)及使用實(shí)戰(zhàn)全面詳解

    本文首先介紹了Django模板系統(tǒng)的基礎(chǔ)知識,接著探討了如何安裝和配置Django模板系統(tǒng),然后深入解析了Django模板的基本結(jié)構(gòu)、標(biāo)簽和過濾器的用法,闡述了如何在模板中展示模型數(shù)據(jù),最后使用一個(gè)實(shí)際項(xiàng)目的例子來演示如何在實(shí)際開發(fā)中使用Django模板系統(tǒng)
    2023-09-09
  • 關(guān)于sklearn包導(dǎo)入錯(cuò)誤:ImportError:?cannot?import?name Type解決方案

    關(guān)于sklearn包導(dǎo)入錯(cuò)誤:ImportError:?cannot?import?name Type解

    這篇文章主要介紹了關(guān)于sklearn包導(dǎo)入錯(cuò)誤:ImportError:?cannot?import?name‘Type‘解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Python和Excel的完美結(jié)合的常用操作案例匯總

    Python和Excel的完美結(jié)合的常用操作案例匯總

    這篇文章主要介紹了Python和Excel的完美結(jié)合的常用操作案例匯總,文章通過圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • django框架中間件原理與用法詳解

    django框架中間件原理與用法詳解

    這篇文章主要介紹了django框架中間件原理與用法,結(jié)合實(shí)例形式詳細(xì)分析了Django框架常用中間件與基本使用技巧,需要的朋友可以參考下
    2019-12-12
  • python 實(shí)現(xiàn)logging動(dòng)態(tài)變更輸出日志文件名

    python 實(shí)現(xiàn)logging動(dòng)態(tài)變更輸出日志文件名

    這篇文章主要介紹了python 實(shí)現(xiàn)logging動(dòng)態(tài)變更輸出日志文件名的案例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • OpenCV霍夫圓變換cv2.HoughCircles()

    OpenCV霍夫圓變換cv2.HoughCircles()

    這篇博客將學(xué)習(xí)如何使用霍夫圓變換在圖像中找到圓圈,OpenCV使用cv2.HoughCircles()實(shí)現(xiàn)霍夫圓變換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07

最新評論

临颍县| 镇沅| 德兴市| 华亭县| 双桥区| 车致| 扶沟县| 双牌县| 荣成市| 定州市| 延川县| 大安市| 璧山县| 嵩明县| 綦江县| 兴义市| 中山市| 尉犁县| 沙坪坝区| 印江| 保定市| 奎屯市| 寿宁县| 鹤壁市| 吉林市| 马公市| 永寿县| 蒲城县| 淮南市| 大庆市| 昭觉县| 临江市| 油尖旺区| 贡嘎县| 会昌县| 怀来县| 惠来县| 娱乐| 武宁县| 夏邑县| 双江|