日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python爬虫验证码的识别_Python爬虫识别验证码

發布時間:2024/9/27 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫验证码的识别_Python爬虫识别验证码 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python爬蟲識別驗證碼

安裝tesserocr

pip3 install tesserocr pillow

識別測試

將驗證碼圖片放到項目根目錄下,用tesserocr庫識別該驗證碼,代碼如下所示:

import locale

locale.setlocale(locale.LC_ALL, 'C')

import tesserocr

from PIL import Image

image = Image.open('code.jpg')

result = tesserocr.image_to_text(image)

print(result)

0

1

2

3

4

5

6

7

importlocale

locale.setlocale(locale.LC_ALL,'C')

importtesserocr

fromPILimportImage

image=Image.open('code.jpg')

result=tesserocr.image_to_text(image)

print(result)

新建了一個Image對象,調用了tesserocr的image_to_text( )方法。傳入該Image對象即可完成識別,實現過程非常簡單,結果如下:

識別的結果和實際結果有偏差,這是因為驗證碼內的多余線條干擾了圖片的識別。

另外,tesserocr還有一個更加簡單的方法,這個方法可以直接將圖片文件轉為字符串,代碼如下:

import locale

locale.setlocale(locale.LC_ALL, 'C')

import tesserocr

from PIL import Image

print(tesserocr.image_to_text('code.jpg'))

0

1

2

3

4

5

importlocale

locale.setlocale(locale.LC_ALL,'C')

importtesserocr

fromPILimportImage

print(tesserocr.image_to_text('code.jpg'))

不過這種方法的識別效果不如上一種的好。

對于上面的圖片,我們可以看到其實并沒有完全識別正確,所以我們需要對圖像作進一步的處理,如灰度轉換、二值化等操作。

我們可以利用Image對象的convert( )方法參數傳入L,即可將圖片轉化為灰度圖像,代碼如下:

image = Image.convert('L')

image.show()

0

1

image=Image.convert('L')

image.show()

傳入1即可將圖片進行二值化處理,如下所示:

image = Image.convert('1')

image.show()

0

1

image=Image.convert('1')

image.show()

我們還可以指定二值化的閾值。上面的方法采用的是默認閾值127。不過我們不能直接轉化原圖,要將原圖先轉化為灰度圖像,然后再指定二值化閾值,代碼如下:

import locale

locale.setlocale(locale.LC_ALL, 'C')

import tesserocr

from PIL import Image

image = Image.open('code.jpg')

image = image.convert('L')

threshold = 160

table = []

for i in range(256):

if i < threshold:

table.append(0)

else:

table.append(1)

image = image.point(table, '1')

image.show()

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

importlocale

locale.setlocale(locale.LC_ALL,'C')

importtesserocr

fromPILimportImage

image=Image.open('code.jpg')

image=image.convert('L')

threshold=160

table=[]

foriinrange(256):

ifi

table.append(0)

else:

table.append(1)

image=image.point(table,'1')

image.show()

在這里,變量threshold代表二值化閾值,閾值設置為160,之后我們來看看我們的結果:

我們可以看到現在的二維碼就比較方便我們進行識別了;那么對于一些有干擾的圖片,我們做一些灰度和二值化處理,這會提高圖片識別的正確率。

總結

以上是生活随笔為你收集整理的python爬虫验证码的识别_Python爬虫识别验证码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。