国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python搭建Keras CNN模型破解網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)

瀏覽:139日期:2022-07-30 18:29:20

在本項(xiàng)目中,將會(huì)用Keras來(lái)搭建一個(gè)稍微復(fù)雜的CNN模型來(lái)破解以上的驗(yàn)證碼。驗(yàn)證碼如下:

Python搭建Keras CNN模型破解網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)

利用Keras可以快速方便地搭建CNN模型,本項(xiàng)目搭建的CNN模型如下:

Python搭建Keras CNN模型破解網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)

將數(shù)據(jù)集分為訓(xùn)練集和測(cè)試集,占比為8:2,該模型訓(xùn)練的代碼如下:

# -*- coding: utf-8 -*-import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom matplotlib import pyplot as plt from keras.utils import np_utils, plot_modelfrom keras.models import Sequentialfrom keras.layers.core import Dense, Dropout, Activation, Flattenfrom keras.callbacks import EarlyStoppingfrom keras.layers import Conv2D, MaxPooling2D # 讀取數(shù)據(jù)df = pd.read_csv(’./data.csv’) # 標(biāo)簽值vals = range(31)keys = [’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,’A’,’B’,’C’,’D’,’E’,’F’,’G’,’H’,’J’,’K’,’L’,’N’,’P’,’Q’,’R’,’S’,’T’,’U’,’V’,’X’,’Y’,’Z’]label_dict = dict(zip(keys, vals)) x_data = df[[’v’+str(i+1) for i in range(320)]]y_data = pd.DataFrame({’label’:df[’label’]})y_data[’class’] = y_data[’label’].apply(lambda x: label_dict[x]) # 將數(shù)據(jù)分為訓(xùn)練集和測(cè)試集X_train, X_test, Y_train, Y_test = train_test_split(x_data, y_data[’class’], test_size=0.3, random_state=42)x_train = np.array(X_train).reshape((1167, 20, 16, 1))x_test = np.array(X_test).reshape((501, 20, 16, 1)) # 對(duì)標(biāo)簽值進(jìn)行one-hot encodingn_classes = 31y_train = np_utils.to_categorical(Y_train, n_classes)y_val = np_utils.to_categorical(Y_test, n_classes) input_shape = x_train[0].shape # CNN模型model = Sequential() # 卷積層和池化層model.add(Conv2D(32, kernel_size=(3, 3), input_shape=input_shape, padding=’same’))model.add(Activation(’relu’))model.add(Conv2D(32, kernel_size=(3, 3), padding=’same’))model.add(Activation(’relu’))model.add(MaxPooling2D(pool_size=(2, 2), padding=’same’)) # Dropout層model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=(3, 3), padding=’same’))model.add(Activation(’relu’))model.add(Conv2D(64, kernel_size=(3, 3), padding=’same’))model.add(Activation(’relu’))model.add(MaxPooling2D(pool_size=(2, 2), padding=’same’)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=(3, 3), padding=’same’))model.add(Activation(’relu’))model.add(Conv2D(128, kernel_size=(3, 3), padding=’same’))model.add(Activation(’relu’))model.add(MaxPooling2D(pool_size=(2, 2), padding=’same’)) model.add(Dropout(0.25)) model.add(Flatten()) # 全連接層model.add(Dense(256, activation=’relu’))model.add(Dropout(0.5))model.add(Dense(128, activation=’relu’))model.add(Dense(n_classes, activation=’softmax’)) model.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[’accuracy’]) # plot model##plot_model(model, to_file=r’./model.png’, show_shapes=True) # 模型訓(xùn)練callbacks = [EarlyStopping(monitor=’val_acc’, patience=5, verbose=1)]batch_size = 64n_epochs = 100history = model.fit(x_train, y_train, batch_size=batch_size, epochs=n_epochs, verbose=1, validation_data=(x_test, y_val), callbacks=callbacks) mp = ’./verifycode_Keras.h5’model.save(mp) # 繪制驗(yàn)證集上的準(zhǔn)確率曲線(xiàn)val_acc = history.history[’val_acc’]plt.plot(range(len(val_acc)), val_acc, label=’CNN model’)plt.title(’Validation accuracy on verifycode dataset’)plt.xlabel(’epochs’)plt.ylabel(’accuracy’)plt.legend()plt.show()

在上述代碼中,訓(xùn)練模型的時(shí)候采用了early stopping技巧。early stopping是用于提前停止訓(xùn)練的callbacks。具體地,可以達(dá)到當(dāng)訓(xùn)練集上的loss不在減小(即減小的程度小于某個(gè)閾值)的時(shí)候停止繼續(xù)訓(xùn)練。

運(yùn)行上述模型訓(xùn)練代碼,輸出的結(jié)果如下:

......(忽略之前的輸出)Epoch 22/100 64/1167 [>.............................] - ETA: 3s - loss: 0.0399 - acc: 1.0000 128/1167 [==>...........................] - ETA: 3s - loss: 0.1195 - acc: 0.9844 192/1167 [===>..........................] - ETA: 2s - loss: 0.1085 - acc: 0.9792 256/1167 [=====>........................] - ETA: 2s - loss: 0.1132 - acc: 0.9727 320/1167 [=======>......................] - ETA: 2s - loss: 0.1045 - acc: 0.9750 384/1167 [========>.....................] - ETA: 2s - loss: 0.1006 - acc: 0.9740 448/1167 [==========>...................] - ETA: 2s - loss: 0.1522 - acc: 0.9643 512/1167 [============>.................] - ETA: 1s - loss: 0.1450 - acc: 0.9648 576/1167 [=============>................] - ETA: 1s - loss: 0.1368 - acc: 0.9653 640/1167 [===============>..............] - ETA: 1s - loss: 0.1353 - acc: 0.9641 704/1167 [=================>............] - ETA: 1s - loss: 0.1280 - acc: 0.9659 768/1167 [==================>...........] - ETA: 1s - loss: 0.1243 - acc: 0.9674 832/1167 [====================>.........] - ETA: 0s - loss: 0.1577 - acc: 0.9639 896/1167 [======================>.......] - ETA: 0s - loss: 0.1488 - acc: 0.9665 960/1167 [=======================>......] - ETA: 0s - loss: 0.1488 - acc: 0.96561024/1167 [=========================>....] - ETA: 0s - loss: 0.1427 - acc: 0.96681088/1167 [==========================>...] - ETA: 0s - loss: 0.1435 - acc: 0.96691152/1167 [============================>.] - ETA: 0s - loss: 0.1383 - acc: 0.96881167/1167 [==============================] - 4s 3ms/step - loss: 0.1380 - acc: 0.9683 - val_loss: 0.0835 - val_acc: 0.9760Epoch 00022: early stopping

可以看到,花費(fèi)幾分鐘,一共訓(xùn)練了21次,最近一次的訓(xùn)練后,在測(cè)試集上的準(zhǔn)確率為96.83%。在測(cè)試集的準(zhǔn)確率曲線(xiàn)如下圖:

Python搭建Keras CNN模型破解網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)

模型訓(xùn)練完后,我們對(duì)新的驗(yàn)證碼進(jìn)行預(yù)測(cè)。新的100張驗(yàn)證碼如下圖:

Python搭建Keras CNN模型破解網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)

使用訓(xùn)練好的CNN模型,對(duì)這些新的驗(yàn)證碼進(jìn)行預(yù)測(cè),預(yù)測(cè)的Python代碼如下:

# -*- coding: utf-8 -*- import osimport cv2import numpy as np def split_picture(imagepath): # 以灰度模式讀取圖片 gray = cv2.imread(imagepath, 0) # 將圖片的邊緣變?yōu)榘咨? height, width = gray.shape for i in range(width): gray[0, i] = 255 gray[height-1, i] = 255 for j in range(height): gray[j, 0] = 255 gray[j, width-1] = 255 # 中值濾波 blur = cv2.medianBlur(gray, 3) #模板大小3*3 # 二值化 ret,thresh1 = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY) # 提取單個(gè)字符 chars_list = [] image, contours, hierarchy = cv2.findContours(thresh1, 2, 2) for cnt in contours: # 最小的外接矩形 x, y, w, h = cv2.boundingRect(cnt) if x != 0 and y != 0 and w*h >= 100: chars_list.append((x,y,w,h)) sorted_chars_list = sorted(chars_list, key=lambda x:x[0]) for i,item in enumerate(sorted_chars_list): x, y, w, h = item cv2.imwrite(’test_verifycode/%d.jpg’%(i+1), thresh1[y:y+h, x:x+w]) def remove_edge_picture(imagepath): image = cv2.imread(imagepath, 0) height, width = image.shape corner_list = [image[0,0] < 127, image[height-1, 0] < 127, image[0, width-1]<127, image[ height-1, width-1] < 127 ] if sum(corner_list) >= 3: os.remove(imagepath) def resplit_with_parts(imagepath, parts): image = cv2.imread(imagepath, 0) os.remove(imagepath) height, width = image.shape file_name = imagepath.split(’/’)[-1].split(r’.’)[0] # 將圖片重新分裂成parts部分 step = width//parts # 步長(zhǎng) start = 0 # 起始位置 for i in range(parts): cv2.imwrite(’./test_verifycode/%s.jpg’%(file_name+’-’+str(i)), image[:, start:start+step]) start += step def resplit(imagepath): image = cv2.imread(imagepath, 0) height, width = image.shape if width >= 64: resplit_with_parts(imagepath, 4) elif width >= 48: resplit_with_parts(imagepath, 3) elif width >= 26: resplit_with_parts(imagepath, 2) # rename and convert to 16*20 sizedef convert(dir, file): imagepath = dir+’/’+file # 讀取圖片 image = cv2.imread(imagepath, 0) # 二值化 ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) img = cv2.resize(thresh, (16, 20), interpolation=cv2.INTER_AREA) # 保存圖片 cv2.imwrite(’%s/%s’ % (dir, file), img) # 讀取圖片的數(shù)據(jù),并轉(zhuǎn)化為0-1值def Read_Data(dir, file): imagepath = dir+’/’+file # 讀取圖片 image = cv2.imread(imagepath, 0) # 二值化 ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) # 顯示圖片 bin_values = [1 if pixel==255 else 0 for pixel in thresh.ravel()] return bin_values def predict(VerifyCodePath): dir = ’./test_verifycode’ files = os.listdir(dir) # 清空原有的文件 if files: for file in files: os.remove(dir + ’/’ + file) split_picture(VerifyCodePath) files = os.listdir(dir) if not files: print(’查看的文件夾為空!’) else: # 去除噪聲圖片 for file in files: remove_edge_picture(dir + ’/’ + file) # 對(duì)黏連圖片進(jìn)行重分割 for file in os.listdir(dir): resplit(dir + ’/’ + file) # 將圖片統(tǒng)一調(diào)整至16*20大小 for file in os.listdir(dir): convert(dir, file) # 圖片中的字符代表的向量 files = sorted(os.listdir(dir), key=lambda x: x[0]) table = np.array([Read_Data(dir, file) for file in files]).reshape(-1,20,16,1) # 模型保存地址 mp = ’./verifycode_Keras.h5’ # 載入模型 from keras.models import load_model cnn = load_model(mp) # 模型預(yù)測(cè) y_pred = cnn.predict(table) predictions = np.argmax(y_pred, axis=1) # 標(biāo)簽字典 keys = range(31) vals = [’1’, ’2’, ’3’, ’4’, ’5’, ’6’, ’7’, ’8’, ’9’, ’A’, ’B’, ’C’, ’D’, ’E’, ’F’, ’G’, ’H’, ’J’, ’K’, ’L’, ’N’,’P’, ’Q’, ’R’, ’S’, ’T’, ’U’, ’V’, ’X’, ’Y’, ’Z’] label_dict = dict(zip(keys, vals)) return ’’.join([label_dict[pred] for pred in predictions]) def main(): dir = ’./VerifyCode/’ correct = 0 for i, file in enumerate(os.listdir(dir)): true_label = file.split(’.’)[0] VerifyCodePath = dir+file pred = predict(VerifyCodePath) if true_label == pred: correct += 1 print(i+1, (true_label, pred), true_label == pred, correct) total = len(os.listdir(dir)) print(’n總共圖片:%d張n識(shí)別正確:%d張n識(shí)別準(zhǔn)確率:%.2f%%.’ %(total, correct, correct*100/total)) main()

以下是該CNN模型的預(yù)測(cè)結(jié)果:

Using TensorFlow backend.2018-10-25 15:13:50.390130: I C: f_jenkinsworkspaceel-winMwindowsPY35 ensorflowcoreplatformcpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX21 (’ZK6N’, ’ZK6N’) True 12 (’4JPX’, ’4JPX’) True 23 (’5GP5’, ’5GP5’) True 34 (’5RQ8’, ’5RQ8’) True 45 (’5TQP’, ’5TQP’) True 56 (’7S62’, ’7S62’) True 67 (’8R2Z’, ’8R2Z’) True 78 (’8RFV’, ’8RFV’) True 89 (’9BBT’, ’9BBT’) True 910 (’9LNE’, ’9LNE’) True 1011 (’67UH’, ’67UH’) True 1112 (’74UK’, ’74UK’) True 1213 (’A5T2’, ’A5T2’) True 1314 (’AHYV’, ’AHYV’) True 1415 (’ASEY’, ’ASEY’) True 1516 (’B371’, ’B371’) True 1617 (’CCQL’, ’CCQL’) True 1718 (’CFD5’, ’GFD5’) False 1719 (’CJLJ’, ’CJLJ’) True 1820 (’D4QV’, ’D4QV’) True 1921 (’DFQ8’, ’DFQ8’) True 2022 (’DP18’, ’DP18’) True 2123 (’E3HC’, ’E3HC’) True 2224 (’E8VB’, ’E8VB’) True 2325 (’DE1U’, ’DE1U’) True 2426 (’FK1R’, ’FK1R’) True 2527 (’FK91’, ’FK91’) True 2628 (’FSKP’, ’FSKP’) True 2729 (’FVZP’, ’FVZP’) True 2830 (’GC6H’, ’GC6H’) True 2931 (’GH62’, ’GH62’) True 3032 (’H9FQ’, ’H9FQ’) True 3133 (’H67Q’, ’H67Q’) True 3234 (’HEKC’, ’HEKC’) True 3335 (’HV2B’, ’HV2B’) True 3436 (’J65Z’, ’J65Z’) True 3537 (’JZCX’, ’JZCX’) True 3638 (’KH5D’, ’KH5D’) True 3739 (’KXD2’, ’KXD2’) True 3840 (’1GDH’, ’1GDH’) True 3941 (’LCL3’, ’LCL3’) True 4042 (’LNZR’, ’LNZR’) True 4143 (’LZU5’, ’LZU5’) True 4244 (’N5AK’, ’N5AK’) True 4345 (’N5Q3’, ’N5Q3’) True 4446 (’N96Z’, ’N96Z’) True 4547 (’NCDG’, ’NCDG’) True 4648 (’NELS’, ’NELS’) True 4749 (’P96U’, ’P96U’) True 4850 (’PD42’, ’PD42’) True 4951 (’PECG’, ’PEQG’) False 4952 (’PPZF’, ’PPZF’) True 5053 (’PUUL’, ’PUUL’) True 5154 (’Q2DN’, ’D2DN’) False 5155 (’QCQ9’, ’QCQ9’) True 5256 (’QDB1’, ’QDBJ’) False 5257 (’QZUD’, ’QZUD’) True 5358 (’R3T5’, ’R3T5’) True 5459 (’S1YT’, ’S1YT’) True 5560 (’SP7L’, ’SP7L’) True 5661 (’SR2K’, ’SR2K’) True 5762 (’SUP5’, ’SVP5’) False 5763 (’T2SP’, ’T2SP’) True 5864 (’U6V9’, ’U6V9’) True 5965 (’UC9P’, ’UC9P’) True 6066 (’UFYD’, ’UFYD’) True 6167 (’V9NJ’, ’V9NH’) False 6168 (’V35X’, ’V35X’) True 6269 (’V98F’, ’V98F’) True 6370 (’VD28’, ’VD28’) True 6471 (’YGHE’, ’YGHE’) True 6572 (’YNKD’, ’YNKD’) True 6673 (’YVXV’, ’YVXV’) True 6774 (’ZFBS’, ’ZFBS’) True 6875 (’ET6X’, ’ET6X’) True 6976 (’TKVC’, ’TKVC’) True 7077 (’2UCU’, ’2UCU’) True 7178 (’HNBK’, ’HNBK’) True 7279 (’X8FD’, ’X8FD’) True 7380 (’ZGNX’, ’ZGNX’) True 7481 (’LQCU’, ’LQCU’) True 7582 (’JNZY’, ’JNZVY’) False 7583 (’RX34’, ’RX34’) True 7684 (’811E’, ’811E’) True 7785 (’ETDX’, ’ETDX’) True 7886 (’4CPR’, ’4CPR’) True 7987 (’FE91’, ’FE91’) True 8088 (’B7XH’, ’B7XH’) True 8189 (’1RUA’, ’1RUA’) True 8290 (’UBCX’, ’UBCX’) True 8391 (’KVT5’, ’KVT5’) True 8492 (’HZ3A’, ’HZ3A’) True 8593 (’3XLR’, ’3XLR’) True 8694 (’VC7T’, ’VC7T’) True 8795 (’7PG1’, ’7PQ1’) False 8796 (’4F21’, ’4F21’) True 8897 (’3HLJ’, ’3HLJ’) True 8998 (’1KT7’, ’1KT7’) True 9099 (’1RHE’, ’1RHE’) True 91100 (’1TTA’, ’1TTA’) True 92總共圖片:100張識(shí)別正確:92張識(shí)別準(zhǔn)確率:92.00%.

可以看到,該訓(xùn)練后的CNN模型,其預(yù)測(cè)新驗(yàn)證的準(zhǔn)確率在90%以上。

Demo及數(shù)據(jù)集下載網(wǎng)站:CNN_4_Verifycode_jb51.rar

到此這篇關(guān)于Python搭建Keras CNN模型破解網(wǎng)站驗(yàn)證碼的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python Keras CNN破解網(wǎng)站驗(yàn)證碼內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 九草视频在线 | 久草97 | a毛片全部播放免费视频完整18 | 在线观看一区二区三区四区 | 国产精品亚洲第五区在线 | 日产一区两区三区四区 | 亚洲男女免费视频 | 久久综合伊人77777 | 99免费在线视频 | 国产精品九九视频 | www.一区| 欧美成人性毛片免费版 | 国产三级做爰在线观看视频 | 欧美一级专区免费大片俄罗斯 | 黄色成人免费网站 | 国内精品自产拍在线观看91 | 黄色毛片视频校园交易 | 免费乱淫视频 | 九九综合| 找个毛片看看 | 免费人成黄页在线观看视频国产 | 亚洲国产精品免费 | 99久久亚洲国产高清观看 | 国产福利不卡一区二区三区 | 香港三级日本三级妇人三级 | 9久9久女女热精品视频免费观看 | 国产亚洲精品久久久久久久久激情 | 欧美成人三级大全 | 国产成人一区二区三区免费观看 | 不卡精品国产_亚洲人成在线 | 国产黄色一级毛片 | 美女视频免费永久观看的 | 国产人成午夜免费噼啪视频 | 国产成人aa在线视频 | 中文国产成人精品久久久 | 超薄肉色丝袜精品足j福利 超级乱淫视频aⅴ播放视频 | 国产精品国产 | 在线观看一级毛片 | 99在线国产视频 | 一区精品视频 | 99久久精品男女性高爱 |