圖形驗證碼的識別


利用OCR技術識別圖形驗證碼

安裝tesserocr

識別測試

import tesserocr
from PIL import Image

image = Image.open('code.jpg')
result = tesserocr.image_to_text(image)
print(result)

也可以直接將圖片文件轉為字符串

import tesserocr
print(tesserocr.file_to_text("image.png"))

驗證碼處理

利用Image對象的convert()方法參數傳入L,即可將圖片轉化為灰度圖像

image = image.convert("L")
image.show()

傳入1可將圖片進行二值化處理

image = image.convert("1")
image.show()

先將原圖轉為灰度圖像,然后再制定二值化閥值。變量 threshold 代表二值化閾值,閾值設置為 80。

image = image.convert('L')
threshold = 80
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)

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

原來驗證碼中的線條已經去除,整個驗證碼變得黑白分明。這時重新識別驗證碼

import tesserocr
from PIL import Image

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

image = image.convert('L')
threshold = 127
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)

image = image.point(table, '1')
result = tesserocr.image_to_text(image)
print(result)

利用專業打碼平台識別驗證碼

日常爬蟲工作中,會遇到目標網站有圖片驗證碼的反爬機制,除了手工配置識別圖片外,為了提高效率,可以通過專業的打碼平台來驗證圖片。這里用阿里雲平台作為例子:

在阿里雲市場有很多專業打碼商品

https://market.aliyun.com/products/?keywords=%E5%9B%BE%E7%89%87%E8%AF%86%E5%88%AB%E9%AA%8C%E8%AF%81%E7%A0%81

選購成功后,記下你的AppCode

接下來開發代碼邏輯:

import urllib.request
import ssl

#修改API說明修改接口地址
url = 'https://imgurlocr.market.alicloudapi.com/urlimages'
method = 'POST'
appcode = '你的AppCode'
querys = ''
bodys = {}


bodys['image'] = '''https://fegine-drug.oss-cn-shanghai.aliyuncs.com/image/urlimage.png'''
post_data = urllib.parse.urlencode(bodys).encode(encoding='UTF8')
request = urllib.request.Request(url, post_data)
#根據API的要求,定義相對應的Content-Type
request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
request.add_header('Authorization', 'APPCODE ' + appcode)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urllib.request.urlopen(request, context=ctx)

content = response.read()
if (content):
    print(content.decode('UTF-8'))

返回結果:

{
  "code": "1",
  "msg": "查詢成功",
  "result_num": 1,
  "result": [
    {
      "words": "給我跪下唱征服"
    }
  ]
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM