cnn进行端到端的验证码识别改进
keras_cnn.py 训练及建模
#!/usr/bin/env python
# coding=utf- """
利用keras cnn进行端到端的验证码识别, 简单直接暴力。
迭代100次可以达到95%的准确率,但是很容易过拟合,泛化能力糟糕, 除了增加训练数据还没想到更好的方法. __autho__: jkmiao
__email__: miao1202@.com
___date__:-- """
from keras.models import Model
from keras.layers import Dense, Dropout, Flatten, Input, merge
from keras.layers import Convolution2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from PIL import Image
import os, random
import numpy as np
from keras.models import model_from_json
from util import CharacterTable
from keras.callbacks import EarlyStopping
from sklearn.model_selection import train_test_split
# from keras.utils.visualize_util import plot def load_data(path='img/clearNoise/'):
fnames = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('jpg')]
random.shuffle(fnames)
data, label = [], []
for i, fname in enumerate(fnames):
imgLabel = fname.split('/')[-].split('_')[]
if len(imgLabel)!=:
print 'error: ', fname
continue
imgM = np.array(Image.open(fname).convert('L'))
imgM = * (imgM>)
data.append(imgM.reshape((, , )))
label.append(imgLabel.lower())
return np.array(data), label ctable = CharacterTable()
data, label = load_data()
print data[].max(), data[].min()
label_onehot = np.zeros((len(label), ))
for i, lb in enumerate(label):
label_onehot[i,:] = ctable.encode(lb)
print data.shape, data[-].max(), data[-].min()
print label_onehot.shape datagen = ImageDataGenerator(shear_range=0.08, zoom_range=0.08, horizontal_flip=False,
rotation_range=, width_shift_range=0.06, height_shift_range=0.06) datagen.fit(data) x_train, x_test, y_train, y_test = train_test_split(data, label_onehot, test_size=0.1) DEBUG = False # 建模
if DEBUG:
input_img = Input(shape=(, , )) inner = Convolution2D(, , , border_mode='same', activation='relu')(input_img)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
encoder_a = Flatten()(inner) inner = Convolution2D(, , , border_mode='same', activation='relu')(input_img)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
encoder_b = Flatten()(inner) inner = Convolution2D(, , , border_mode='same', activation='relu')(input_img)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
encoder_c = Flatten()(inner) input = merge([encoder_a, encoder_b, encoder_c], mode='concat', concat_axis=-)
drop = Dropout(0.5)(input)
flatten = Dense()(drop)
flatten = Dropout(0.5)(flatten) fc1 = Dense(, activation='softmax')(flatten)
fc2 = Dense(, activation='softmax')(flatten)
fc3 = Dense(, activation='softmax')(flatten)
fc4 = Dense(, activation='softmax')(flatten)
fc5 = Dense(, activation='softmax')(flatten)
fc6 = Dense(, activation='softmax')(flatten)
merged = merge([fc1, fc2, fc3, fc4, fc5, fc6], mode='concat', concat_axis=-) model = Model(input=input_img, output=merged)
else:
model = model_from_json(open('model/ba_cnn_model3.json').read())
model.load_weights('model/ba_cnn_model3.h5') # 编译
# model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # plot(model, to_file='model3.png', show_shapes=True) # 训练 early_stopping = EarlyStopping(monitor='val_loss', patience=) model.fit_generator(datagen.flow(x_train, y_train, batch_size=), samples_per_epoch=len(x_train), nb_epoch=, validation_data=(x_test, y_test), callbacks=[early_stopping] ) json_string = model.to_json()
with open('./model/ba_cnn_model4.json', 'w') as fw:
fw.write(json_string)
model.save_weights('./model/ba_cnn_model4.h5') print 'done saved model cnn3' # 测试
y_pred = model.predict(x_test, verbose=)
cnt =
for i in range(len(y_pred)):
guess = ctable.decode(y_pred[i])
correct = ctable.decode(y_test[i])
if guess == correct:
cnt +=
if i%==:
print '--'*, i
print 'y_pred', guess
print 'y_test', correct
print cnt/float(len(y_pred))
apicode.py 模型使用
#!/usr/bin/env python
# coding=utf- from util import CharacterTable
from keras.models import model_from_json
from PIL import Image
import matplotlib.pyplot as plt
import os
import numpy as np
from prepare import clearNoise def img2vec(fname):
data = []
img = clearNoise(fname).convert('L')
imgM = 1.0 * (np.array(img)>)
print imgM.max(), imgM.min()
data.append(imgM.reshape((, , )))
return np.array(data), imgM ctable = CharacterTable() model = model_from_json(open('model/ba_cnn_model4.json').read())
model.load_weights('model/ba_cnn_model4.h5') def test(path):
fnames = [ os.path.join(path, fname) for fname in os.listdir(path) ][:]
correct =
for idx, fname in enumerate(fnames, ):
data, imgM = img2vec(fname)
y_pred = model.predict(data)
result = ctable.decode(y_pred[])
label = fname.split('/')[-].split('_')[]
if result == label:
correct +=
print 'correct', fname
else:
print result, label
print 'accuracy: ',idx, float(correct)/idx
print '=='*
# plt.subplot()
# plt.imshow(Image.open(fname).convert('L'), plt.cm.gray)
# plt.title(fname)
#
# plt.subplot()
# plt.imshow(imgM, plt.cm.gray)
# plt.title(result)
# plt.show() test('test')
cnn进行端到端的验证码识别改进的更多相关文章
- 基于tensorflow的‘端到端’的字符型验证码识别源码整理(github源码分享)
基于tensorflow的‘端到端’的字符型验证码识别 1 Abstract 验证码(CAPTCHA)的诞生本身是为了自动区分 自然人 和 机器人 的一套公开方法, 但是近几年的人工智能技术的发展 ...
- 基于python语言的tensorflow的‘端到端’的字符型验证码识别源码整理(github源码分享)
基于python语言的tensorflow的‘端到端’的字符型验证码识别 1 Abstract 验证码(CAPTCHA)的诞生本身是为了自动区分 自然人 和 机器人 的一套公开方法, 但是近几年的 ...
- CNN+BLSTM+CTC的验证码识别从训练到部署
项目地址:https://github.com/kerlomz/captcha_trainer 1. 前言 本项目适用于Python3.6,GPU>=NVIDIA GTX1050Ti,原mast ...
- 【转】CNN+BLSTM+CTC的验证码识别从训练到部署
[转]CNN+BLSTM+CTC的验证码识别从训练到部署 转载地址:https://www.jianshu.com/p/80ef04b16efc 项目地址:https://github.com/ker ...
- [验证码识别技术] 字符型验证码终结者-CNN+BLSTM+CTC
验证码识别(少样本,高精度)项目地址:https://github.com/kerlomz/captcha_trainer 1. 前言 本项目适用于Python3.6,GPU>=NVIDIA G ...
- Python实现各类验证码识别
项目地址: https://github.com/kerlomz/captcha_trainer 编译版下载地址: https://github.com/kerlomz/captcha_trainer ...
- 基于SVM的字母验证码识别
基于SVM的字母验证码识别 摘要 本文研究的问题是包含数字和字母的字符验证码的识别.我们采用的是传统的字符分割识别方法,首先将图像中的字符分割出来,然后再对单字符进行识别.首先通过图像的初步去噪.滤波 ...
- [验证码识别技术]字符验证码杀手--CNN
字符验证码杀手--CNN 1 abstract 目前随着深度学习,越来越蓬勃的发展,在图像识别和语音识别中也表现出了强大的生产力.对于普通的深度学习爱好者来说,一上来就去跑那边公开的大型数据库,比如I ...
- 强智教务系统验证码识别 Tensorflow CNN
强智教务系统验证码识别 Tensorflow CNN 一直都是使用API取得数据,但是API提供的数据较少,且为了防止API关闭,先把验证码问题解决 使用Tensorflow训练模型,强智教务系统的验 ...
随机推荐
- python猜数字(多种实现方法)
设定一个理想数字比如:66,让用户输入数字,如果比66⼤,则显示猜测的结果⼤了:如果比66⼩,则显示猜测的结果小了;只有等于66,显示猜测结果 第一种方式(最简单的方式实现) n = 66 # 理想数 ...
- LG4781 【模板】拉格朗日插值
题意 题目描述 由小学知识可知,$n$个点$(x_i,y_i)$可以唯一地确定一个多项式 现在,给定$n$个点,请你确定这个多项式,并将$k$代入求值 求出的值对$998244353$取模 输入输出格 ...
- 转载 React.createClass 对决 extends React.Component
先给出结论,这其实是殊途同归的两种方式.过去我们一般都会使用 React.createClass 方法来创建组件,但基于 ES6 的小小语法糖,我们还可以通过 extends React.Compon ...
- Java-简单的计算器(只能进行加法运算)
有两个关键的地方: 其一: JTextField field=new JTextField(10); 这是一个文本输入框,里面的参数10的意思是,这个输入框的长度为10列 其二:点击求和按钮,出结果 ...
- pghoard 面向云存储的pg 备份&&恢复工具
pghoard 面向云存储的pg 备份&&恢复工具 包含的特性 自动定期basebackup 自动事务日志(WAL / Xlog软件)备份(使用pg_receivexlog, arch ...
- Vision GUI programming products
Matrox Design Assistant Tutorial https://www.youtube.com/watch?v=QnE5heA_yWQ merlic https://www.yout ...
- Nginx浏览目录配置及美化
https://segmentfault.com/a/1190000012606305 在项目中有一个功能需要在浏览器页面中浏览服务器的目录.服务器使用Nginx,而Nginx提供了相应的ngx_ht ...
- c++获取键盘输入cin、scanf使用详解
cin是c++标准,scanf是在c中使用的 #include<cstdio> #include<iostream> #include<cstring> using ...
- C语言中基本的数据类型
一般来说,一个C的工程中一定要做一些这方面的工作,因为你会涉及到跨平台,不同的平台会有不同的字长,所以利用预编译和typedef可以让你最有效的维护你的代码.为了用户的方便,C99标准的C语言硬件为我 ...
- 外同步信号检测---verilog---状态机
外同步信号检测---verilog---状态机 `timescale 1ns / 1ps /////////////////////////////////////////////////////// ...