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爬虫识别验证码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lambda 流 peek java_J
- 下一篇: python导入pillow模块_Pyt