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训练模型,强智教务系统的验 ...
随机推荐
- R49 A-D D图有向有环图
A. Palindromic Twist 给一个字符串(小写字母) 每个字符+1,-1:变成其他字符 a只能变b z只能变y 看能否变成回文字符串 #include<bits/stdc+ ...
- 重写&重载
重写:子类对父类或接口中方法重新定义,是同一个方法 (1)子类不能重写final方法 (2)子类必须重写abstract方法 重载:一个类内部,方法同名,参数列表不同 (1)返回值不能作为区分重载方法 ...
- java gaoji 算法
import java.util.Scanner; public class Main{ public static int[] Test(int[] a){ int [] ...
- Go Example--递归
package main import "fmt" func main() { fmt.Println(fact(7)) } //函数的递归 func fact(n int) in ...
- 【BZOJ4300】 绝世好题
傻逼题都不能一眼看出思路…… 原题: 给定一个长度为n的数列ai,求ai的子序列bi的最长长度,满足bi&bi-1!=0(2<=i<=len). n<=100000,ai&l ...
- Mybatis一(基础)
mybatis架构 1.mybatis配置 SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息. mapper.xml文件即sql映射文件, ...
- JQuery城市选择
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Running Elixir in Docker Containers
转自:https://www.poeticoding.com/running-elixir-in-docker-containers/ One of the wonderful things abou ...
- Singer 学习十一 配置以及状态管理
配置和状态文件通过提供身份验证信息,开始时间和有关以前调用的信息,帮助为Taps和Targets提供上下文 配置文件 配置文件包含tap 运行需要的信息,通常包含API,以及数据源的凭据 特殊字段 s ...
- Python __name__变量
原文: http://blog.csdn.net/u011511601/article/details/53504355 Python使用缩进对齐组织代码的执行,所有没有缩进的代码,都会在载入时自动执 ...