python簡(jiǎn)單驗(yàn)證碼識(shí)別的實(shí)現(xiàn)方法
利用SVM向量機(jī)進(jìn)行4位數(shù)字驗(yàn)證碼識(shí)別
主要是思路和步驟如下:
一,素材收集
檢查環(huán)境是否包含有相應(yīng)的庫(kù):
1.在cmd中,通過(guò) pip list命令查看安裝的庫(kù)
2.再使用pip installRequests 安裝Requests庫(kù)
3.再次使用pip list 命令

4.利用python獲取驗(yàn)證碼資源
編寫(xiě)代碼:_DownloadPic.py
#!/usr/bin/nev python3
#利用python從站點(diǎn)下載驗(yàn)證碼圖片
import requests
## 1.在 http://www.xxx.com
# 獲取驗(yàn)證碼URL
def Downloads_Pic(strPath, strName):
#設(shè)置url
url = 'http://www.xxx.com'
#以二進(jìn)制方式發(fā)送Get請(qǐng)求,
#將stream = True,
#數(shù)據(jù)讀取完成前不要斷開(kāi)鏈接
rReq = requests.get(url, stream = True)
#嘗試保存圖片
with open(strPath + strName + '.png', 'wb') as fpPic:
#循環(huán)讀取1024Byte到byChunk中,讀完則跳出
for byChunk in rReq.iter_content(chunk_size = 1024):
if byChunk:
fpPic.write(byChunk)
fpPic.flush()
fpPic.close()
for i in range(1, 10 + 1):
strFileName = "%03d" % i
Downloads_Pic('D:/1/', strFileName)
二,素材處理
1.二值化處理,增加對(duì)比度,銳化,增加亮度,濾鏡,轉(zhuǎn)為黑白
2.去除噪點(diǎn)
3.切割圖片

編寫(xiě)代碼:_PicDealWith.py
#!/usr/bin/env python3
import os
import os.path
from PIL import Image, ImageEnhance, ImageFilter
import random
#二值化處理
#strImgPath 圖片路徑
def BinaryzationImg(strImgPath):
#打開(kāi)圖片
imgOriImg = Image.open(strImgPath)
#增加對(duì)比度
pocEnhance = ImageEnhance.Contrast(imgOriImg)
#增加255%對(duì)比度
imgOriImg = pocEnhance.enhance(2.55)
#銳化
pocEnhance = ImageEnhance.Sharpness(imgOriImg)
#銳化200%
imgOriImg = pocEnhance.enhance(2.0)
#增加亮度
pocEnhance = ImageEnhance.Brightness(imgOriImg)
#增加200%
imgOriImg = pocEnhance.enhance(2.0)
#添加濾鏡效果
imgGryImg = imgOriImg.convert('L').filter(ImageFilter.DETAIL)
#二值化處理
imgBinImg = imgGryImg.convert('1')
return imgBinImg
#去除噪點(diǎn)
def ClearNoise(imgBinImg):
for x in range(1, (imgBinImg.size[0]-1)):
for y in range(1,(imgBinImg.size[1] - 1)):
#一個(gè)點(diǎn)為黑色,周?chē)?個(gè)點(diǎn)為白色,則此點(diǎn)為噪點(diǎn),設(shè)置為白色
if imgBinImg.getpixel((x, y)) == 0 \
and imgBinImg.getpixel(((x - 1), (y + 1))) == 255 \
and imgBinImg.getpixel(((x - 1), y)) == 255 \
and imgBinImg.getpixel(((x - 1), (y - 1))) == 255 \
and imgBinImg.getpixel(((x + 1), (y + 1))) == 255 \
and imgBinImg.getpixel(((x + 1), y)) == 255 \
and imgBinImg.getpixel(((x + 1), (y - 1))) == 255 \
and imgBinImg.getpixel((x, (y + 1))) == 255 \
and imgBinImg.getpixel((x, (y - 1))) == 255:
imgBinImg.putpixel([x, y], 255)
return imgBinImg
#切割圖片
def GetCropImgs(imgClrImg):
ImgList = []
for i in range(4):
x = 6 + i * 13
y = 3
SubImg = imgClrImg.crop((x, y, x + 13, y + 15))
ImgList.append(SubImg)
return ImgList
#調(diào)用部分
def main():
g_Count = 0
strStep1Dir = 'D:/1/step1/'
strStep2Dir = 'D:/1/step2/'
for ParentPath, DirName, FileNames in os.walk(strStep1Dir):
for i in FileNames:
#圖片文件路徑信息
strFullPath = os.path.join(ParentPath, i)
imgBinImg = BinaryzationImg(strFullPath)
imgClrImg = ClearNoise(imgBinImg)
ImgList = GetCropImgs(imgClrImg)
for img in ImgList:
strImgName = "%04d%04d.png" % (g_Count, random.randint(0, 9999))
strImgPath = os.path.join(strStep2Dir, strImgName)
img.save(strImgPath)
g_Count += 1
print("OK!")
if __name__ == '__mian__':
main()
三,手工分類(lèi)
將第二步切割好的圖片進(jìn)行分類(lèi),體力活

四,利用SVM向量機(jī)建立模型
1.安裝svm庫(kù)
下載libsvm庫(kù),并解壓
將庫(kù)中的windows目錄的路徑添加到path環(huán)境變量中
將libsvm下的python文件夾中的svm.py和svmutil.py文件拷貝到你的python的路徑中l(wèi)ib文件夾中
from svmutil import *
2.生成模型文件
2.1.將分好類(lèi)的圖片信息進(jìn)行提取,生成特征值
2.2.輸出向量數(shù)據(jù)

2.3.根據(jù)數(shù)據(jù)輸出SVM模型文件
編寫(xiě)代碼:_SVMDemo.py
#!/usr/bin/env python3
#SVM,驗(yàn)證碼識(shí)別
import os
import sys
import random
import os.path
from PIL import Image, ImageEnhance, ImageFilter
from svmutil import *
##記錄像素點(diǎn)的值,描述特征,采用遍歷每個(gè)像素點(diǎn)統(tǒng)計(jì)黑色點(diǎn)的數(shù)量
def GetFeature(imgCropImg, nImgHeight, nImgWidth):
PixelCountList = []
for y in range(nImgHeight):
CountX = 0
for x in range(nImgWidth):
if imgCropImg.getpixel((x, y)) == 0:
CountX += 1
PixelCountList.append(CountX)
for x in range(nImgWidth):
CountY = 0
for y in range(nImgHeight):
if imgCropImg.getpixel((x, y)) == 0:
CountY += 1
PixelCountList.append(CountY)
return PixelCountList
##輸出向量數(shù)據(jù)
def OutPutVectorData(strID, strMaterialDir, strOutPath):
for ParentPath, DirNames, FileNames in os.walk(strMaterialDir):
with open(strOutPath, 'a') as fpFea:
for fp in FileNames:
#圖片文件路徑信息
strFullPath = os.path.join(ParentPath, fp)
#打開(kāi)圖片
imgOriImg = Image.open(strFullPath)
#生成特征值
FeatureList = GetFeature(imgOriImg, 15, 13)
strFeature = strID + ' '
nCount = 1
for i in FeatureList:
strFeature = '%s%d:%d ' % (strFeature, nCount, i)
nCount += 1
fpFea.write(strFeature + '\n')
fpFea.flush()
fpFea.close()
#訓(xùn)練SVM模型
def TrainSvmModel(strProblemPath, strModelPath):
Y, X = svm_read_problem(strProblemPath)
Model = svm_train(Y, X)
svm_save_model(strModelPath, Model)
#SVM模型測(cè)試
def SvmModelTest(strProblemPath, strModelPath):
TestY, TestX = svm_read_problem(strProblemPath)
Model = svm_load_model(strModelPath)
#返回識(shí)別結(jié)果
pLabel, pAcc, pVal = svm_predict(TestY, TestX, Model)
return pLabel
##輸出測(cè)試向量數(shù)據(jù)
def OutPutTestVectorData(strID, strDir, strOutPath):
fileList = []
for parentPath, strDir, fileName in os.walk(strDir):
fileList = fileName
with open(strOutPath, 'a') as fpFea:
for fp in fileList:
#圖片文件路徑信息
strFullPath = os.path.join(parentPath, fp)
#打開(kāi)圖片
imgOriImg = Image.open(strFullPath)
#生成特征值
FeatureList = GetFeature(imgOriImg, 15, 13)
strFeature = strID + ' '
nCount = 1
for i in FeatureList:
strFeature = '%s%d:%d ' % (strFeature, nCount, i)
nCount += 1
fpFea.write(strFeature + '\n')
fpFea.flush()
fpFea.close()
def main():
# 1.循環(huán)輸出向量文件
for i in range(0, 10):
strID = '%d' % i
OutPutVectorData(strID, 'D:/1/step3/' + strID, 'D:/1/step4/Vector.txt')
# 2.調(diào)用函數(shù)訓(xùn)練SVM模型
TrainSvmModel('D:/1/step4/Vector.txt', 'D:/1/step5/Model.txt')
# 3.調(diào)用函數(shù)識(shí)別結(jié)果
pLabel = SvmModelTest('D:/1/step6/Vector.txt', 'D:/1/step5/Model.txt')
for i in pLabel:
print('%d' % i)
if __name__ == '__main__':
main()
五,測(cè)試
1.利用模型文件和向量文件進(jìn)行測(cè)試驗(yàn)證碼識(shí)別
##1.獲取一張驗(yàn)證碼圖片
##2.對(duì)圖片進(jìn)行處理
## 2.1.二值化處理,增加對(duì)比度,銳化,增加亮度,濾鏡,轉(zhuǎn)為黑白,
## 2.2.去除噪點(diǎn)
## 2.3.切割圖片
##3.生成向量文件
##4.再利用之前的模型文件進(jìn)行識(shí)別測(cè)試
編寫(xiě)代碼:_SVMTest.py
#!/usr/bin/env python3
#對(duì)一張驗(yàn)證碼圖片進(jìn)行識(shí)別測(cè)試
##1.獲取一張驗(yàn)證碼圖片
##2.對(duì)圖片進(jìn)行處理
## 2.1.二值化處理,增加對(duì)比度,銳化,增加亮度,濾鏡,轉(zhuǎn)為黑白,
## 2.2.去除噪點(diǎn)
## 2.3.切割圖片
##3.生成向量文件
##4.再利用之前的模型文件進(jìn)行識(shí)別測(cè)試
################
import _PicDealWith
import os
import random
import _SVMDemo
##測(cè)試
g_Count = 0
strDirPath = 'D:/1/test/'
strFileName = '001.png'
#1.圖片文件路徑信息
strFullPath = os.path.join(strDirPath, strFileName)
#2.對(duì)圖片進(jìn)行處理
#2.1二值化處理
imgBinImg = _PicDealWith.BinaryzationImg(strFullPath)
#2.2去除噪點(diǎn)
imgClrImg = _PicDealWith.ClearNoise(imgBinImg)
#2.3切割圖片
ImgList = _PicDealWith.GetCropImgs(imgClrImg)
#2.3循環(huán)寫(xiě)入文件
for img in ImgList:
strImgName = "%04d%04d.png" % (g_Count, random.randint(0, 9999))
strImgPath = os.path.join(strDirPath, strImgName)
img.save(strImgPath)
g_Count += 1
print("OK")
os.remove(strFullPath)
#3.生成向量文件
_SVMDemo.OutPutTestVectorData('0', 'D:/1/test/', 'D:/1/test/Vector.txt')
#4.利用之前的模型文件進(jìn)行識(shí)別測(cè)試
pLabel = _SVMDemo.SvmModelTest('D:/1/test/Vector.txt', 'D:/1/step5/Model.txt')
for i in pLabel:
print('%d' % i, end = '')
效果圖:

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Autopep8的使用(python自動(dòng)編排工具)
這篇文章主要介紹了Autopep8的使用(python自動(dòng)編排工具),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
對(duì)Python+opencv將圖片生成視頻的實(shí)例詳解
今天小編就為大家分享一篇對(duì)Python+opencv將圖片生成視頻的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
教你用Python爬取英雄聯(lián)盟皮膚原畫(huà)
今天給大家?guī)?lái)的是關(guān)于Python的相關(guān)知識(shí),文章圍繞著用Python爬取英雄聯(lián)盟皮膚原畫(huà)展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
基于Python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了如何利用python實(shí)現(xiàn)簡(jiǎn)單的學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-12-12
Python數(shù)據(jù)的標(biāo)準(zhǔn)輸出與格式化輸出
這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)的標(biāo)準(zhǔn)輸出與格式化輸出的相關(guān)資料,和大多數(shù)語(yǔ)言一樣,Python也是用print()函數(shù)來(lái)進(jìn)行輸出,需要的朋友可以參考下2023-08-08
Python分支結(jié)構(gòu)和循環(huán)結(jié)構(gòu)示例代碼
在Python中,分支結(jié)構(gòu)通過(guò)if、elif和else關(guān)鍵字來(lái)實(shí)現(xiàn)條件判斷,在使用if語(yǔ)句時(shí),程序會(huì)根據(jù)條件表達(dá)式的真假執(zhí)行相應(yīng)的代碼塊,這篇文章主要介紹了Python分支結(jié)構(gòu)和循環(huán)結(jié)構(gòu),需要的朋友可以參考下2024-03-03
Python內(nèi)置模塊ConfigParser實(shí)現(xiàn)配置讀寫(xiě)功能的方法
這篇文章主要介紹了Python內(nèi)置模塊ConfigParser實(shí)現(xiàn)配置讀寫(xiě)功能的方法,涉及Python使用ConfigParser模塊進(jìn)行配置讀、寫(xiě)、修改、刪除等操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-02-02
淺談python3打包與拆包在函數(shù)的應(yīng)用詳解
這篇文章主要介紹了淺談python3打包與拆包在函數(shù)的應(yīng)用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05

