当前位置: 首页 > news >正文

湘潭市网站建设_网站建设公司_网站建设_seo优化

怎么制作购物网站,广东阳江发布,天津常规网站建设系列,做招商如何选择网站本项目介绍利用深度学习技术#xff08;tensorflow#xff09;#xff0c;来识别验证码#xff08;4位验证码#xff0c;具体的验证码的长度可以自己生成#xff0c;可以在自己进行训练#xff09; 程序分为四个部分 1、生成验证码的程序#xff0c;可生成数字字母大…本项目介绍利用深度学习技术tensorflow来识别验证码4位验证码具体的验证码的长度可以自己生成可以在自己进行训练 程序分为四个部分 1、生成验证码的程序可生成数字字母大小写的任意长度验证码 # coding:utf-8 # name:captcha_gen.pyimport random import numpy as np from PIL import Image from captcha.image import ImageCaptchaNUMBER [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] LOW_CASE [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,v, w, x, y, z] UP_CASE [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U,V, W, X, Y, Z]CAPTCHA_LIST NUMBER CAPTCHA_LEN 4 # 验证码长度 CAPTCHA_HEIGHT 60 # 验证码高度 CAPTCHA_WIDTH 160 # 验证码宽度def random_captcha_text(char_setCAPTCHA_LIST, captcha_sizeCAPTCHA_LEN):随机生成定长字符串:param char_set: 备选字符串列表:param captcha_size: 字符串长度:return: 字符串captcha_text [random.choice(char_set) for _ in range(captcha_size)]return .join(captcha_text)def gen_captcha_text_and_image(widthCAPTCHA_WIDTH, heightCAPTCHA_HEIGHT, saveNone):生成随机验证码:param width: 验证码图片宽度:param height: 验证码图片高度:param save: 是否保存None:return: 验证码字符串验证码图像np数组image ImageCaptcha(widthwidth, heightheight)# 验证码文本captcha_text random_captcha_text()captcha image.generate(captcha_text)# 保存if save:image.write(captcha_text, ./img/ captcha_text .jpg)captcha_image Image.open(captcha)# 转化为np数组captcha_image np.array(captcha_image)return captcha_text, captcha_imageif __name__ __main__:t, im gen_captcha_text_and_image(saveTrue)print(t, im.shape) # (60, 160, 3)2、工具库用于调用验证码生成程序来生成训练集 # -*- coding:utf-8 -*- # name: util.pyimport numpy as np from captcha_gen import gen_captcha_text_and_image from captcha_gen import CAPTCHA_LIST, CAPTCHA_LEN, CAPTCHA_HEIGHT, CAPTCHA_WIDTHdef convert2gray(img):图片转为黑白3维转1维:param img: np:return: 灰度图的npif len(img.shape) 2:img np.mean(img, -1)return imgdef text2vec(text, captcha_lenCAPTCHA_LEN, captcha_listCAPTCHA_LIST):验证码文本转为向量 哑编码 方式:param text::param captcha_len::param captcha_list::return: vector 文本对应的向量形式text_len len(text) # 欲生成验证码的字符长度if text_len captcha_len:raise ValueError(验证码最长4个字符)vector np.zeros(captcha_len * len(captcha_list)) # 生成一个一维向量 验证码长度*字符列表长度for i in range(text_len):vector[captcha_list.index(text[i])i*len(captcha_list)] 1 # 找到字符对应在字符列表中的下标值字符列表长度*i 的 一维向量 赋值为 1return vectordef vec2text(vec, captcha_listCAPTCHA_LIST, captcha_lenCAPTCHA_LEN):验证码向量转为文本:param vec::param captcha_list::param captcha_len::return: 向量的字符串形式vec_idx vectext_list [captcha_list[int(v)] for v in vec_idx]return .join(text_list)def wrap_gen_captcha_text_and_image(shape(CAPTCHA_HEIGHT, CAPTCHA_WIDTH, 3)):返回特定shape图片:param shape::return:while True:t, im gen_captcha_text_and_image()if im.shape shape:return t, imdef get_next_batch(batch_count60, widthCAPTCHA_WIDTH, heightCAPTCHA_HEIGHT):获取训练图片组:param batch_count: default 60:param width: 验证码宽度:param height: 验证码高度:return: batch_x, batch_ycbatch_x np.zeros([batch_count, width * height])batch_y np.zeros([batch_count, CAPTCHA_LEN * len(CAPTCHA_LIST)])for i in range(batch_count): # 生成对应的训练集text, image wrap_gen_captcha_text_and_image()image convert2gray(image) # 转灰度numpy# 将图片数组一维化 同时将文本也对应在两个二维组的同一行batch_x[i, :] image.flatten() / 255batch_y[i, :] text2vec(text) # 验证码文本的向量形式# 返回该训练批次return batch_x, batch_yif __name__ __main__:x, y get_next_batch(batch_count1) # 默认为1用于测试集print(x, y) 3、训练程序并将准确率超过0.95的模型保存到 ./model/ 文件夹下 # -*- coding:utf-8 -*- # name: model_train.pyimport tensorflow as tf from datetime import datetime from util import get_next_batch from captcha_gen import CAPTCHA_HEIGHT, CAPTCHA_WIDTH, CAPTCHA_LEN, CAPTCHA_LISTdef weight_variable(shape, w_alpha0.01):初始化权值:param shape::param w_alpha::return:initial w_alpha * tf.random_normal(shape)return tf.Variable(initial)def bias_variable(shape, b_alpha0.1):初始化偏置项:param shape::param b_alpha::return:initial b_alpha * tf.random_normal(shape)return tf.Variable(initial)def conv2d(x, w):卷基层 局部变量线性组合步长为1模式‘SAME’代表卷积后图片尺寸不变即零边距:param x::param w::return:return tf.nn.conv2d(x, w, strides[1, 1, 1, 1], paddingSAME)def max_pool_2x2(x):池化层max pooling,取出区域内最大值为代表特征 2x2 的pool图片尺寸变为1/2:param x::return:return tf.nn.max_pool(x, ksize[1, 2, 2, 1], strides[1, 2, 2, 1], paddingSAME)def cnn_graph(x, keep_prob, size, captcha_listCAPTCHA_LIST, captcha_lenCAPTCHA_LEN):三层卷积神经网络:param x: 训练集 image x:param keep_prob: 神经元利用率:param size: 大小 (高,宽):param captcha_list::param captcha_len::return: y_conv# 需要将图片reshape为4维向量image_height, image_width sizex_image tf.reshape(x, shape[-1, image_height, image_width, 1])# 第一层# filter 定义为3x3x1 输出32个特征, 即32个filterw_conv1 weight_variable([3, 3, 1, 32]) # 3*3的采样窗口32个通道卷积核从1个平面抽取特征得到32个特征平面b_conv1 bias_variable([32])h_conv1 tf.nn.relu(conv2d(x_image, w_conv1) b_conv1) # rulu激活函数h_pool1 max_pool_2x2(h_conv1) # 池化h_drop1 tf.nn.dropout(h_pool1, keep_prob) # dropout 防止过拟合# 第二层w_conv2 weight_variable([3, 3, 32, 64])b_conv2 bias_variable([64])h_conv2 tf.nn.relu(conv2d(h_drop1, w_conv2) b_conv2)h_pool2 max_pool_2x2(h_conv2)h_drop2 tf.nn.dropout(h_pool2, keep_prob)# 第三层w_conv3 weight_variable([3, 3, 64, 64])b_conv3 bias_variable([64])h_conv3 tf.nn.relu(conv2d(h_drop2, w_conv3) b_conv3)h_pool3 max_pool_2x2(h_conv3)h_drop3 tf.nn.dropout(h_pool3, keep_prob)原始60*160图片 第一次卷积后 60*160 第一池化后 30*80*32第二次卷积后 30*80*32 第二次池化后 15*40*64第三次卷积后 15*40*64 第三次池化后 7.5*20*64 向下取整 7*20*64经过上面操作后得到 64 个 7*20的平面# 全连接层image_height int(h_drop3.shape[1])image_width int(h_drop3.shape[2])w_fc weight_variable([image_height*image_width*64, 1024]) # 上一层有64个神经元 全连接层有1024个神经元b_fc bias_variable([1024])h_drop3_re tf.reshape(h_drop3, [-1, image_height*image_width*64])h_fc tf.nn.relu(tf.matmul(h_drop3_re, w_fc) b_fc)h_drop_fc tf.nn.dropout(h_fc, keep_prob)# 输出层w_out weight_variable([1024, len(captcha_list)*captcha_len])b_out bias_variable([len(captcha_list)*captcha_len])y_conv tf.matmul(h_drop_fc, w_out) b_outreturn y_convdef optimize_graph(y, y_conv):优化计算图:param y: 正确值:param y_conv: 预测值:return: optimizer# 交叉熵代价函数计算loss 注意 logits 输入是在函数内部进行sigmod操作# sigmod_cross适用于每个类别相互独立但不互斥如图中可以有字母和数字# softmax_cross适用于每个类别独立且排斥的情况如数字和字母不可以同时出现loss tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labelsy, logitsy_conv))# 最小化loss优化 AdaminOptimizer优化optimizer tf.train.AdamOptimizer(1e-3).minimize(loss)return optimizerdef accuracy_graph(y, y_conv, widthlen(CAPTCHA_LIST), heightCAPTCHA_LEN):偏差计算图正确值和预测值计算准确度:param y: 正确值 标签:param y_conv: 预测值:param width: 验证码预备字符列表长度:param height: 验证码的大小默认为4:return: 正确率# 这里区分了大小写 实际上验证码一般不区分大小写,有四个值不同于手写体识别# 预测值predict tf.reshape(y_conv, [-1, height, width]) #max_predict_idx tf.argmax(predict, 2)# 标签label tf.reshape(y, [-1, height, width])max_label_idx tf.argmax(label, 2)correct_p tf.equal(max_predict_idx, max_label_idx) # 判断是否相等accuracy tf.reduce_mean(tf.cast(correct_p, tf.float32))return accuracydef train(heightCAPTCHA_HEIGHT, widthCAPTCHA_WIDTH, y_sizelen(CAPTCHA_LIST)*CAPTCHA_LEN):cnn训练:param height: 验证码高度:param width: 验证码宽度:param y_size: 验证码预备字符列表长度*验证码长度默认为4:return:# cnn在图像大小是2的倍数时性能最高, 如果图像大小不是2的倍数可以在图像边缘补无用像素# 在图像上补2行下补3行左补2行右补2行# np.pad(image,((2,3),(2,2)), constant, constant_values(255,))acc_rate 0.95 # 预设模型准确率标准# 按照图片大小申请占位符x tf.placeholder(tf.float32, [None, height * width])y tf.placeholder(tf.float32, [None, y_size])# 防止过拟合 训练时启用 测试时不启用 神经元使用率keep_prob tf.placeholder(tf.float32)# cnn 模型y_conv cnn_graph(x, keep_prob, (height, width))# 优化optimizer optimize_graph(y, y_conv)# 计算准确率accuracy accuracy_graph(y, y_conv)# 启动会话.开始训练saver tf.train.Saver()sess tf.Session()sess.run(tf.global_variables_initializer()) # 初始化step 0 # 步数while 1:print(step)batch_x, batch_y get_next_batch(64)sess.run(optimizer, feed_dict{x: batch_x, y: batch_y, keep_prob: 0.75})# 每训练一百次测试一次if step % 10 0:batch_x_test, batch_y_test get_next_batch(100)acc sess.run(accuracy, feed_dict{x: batch_x_test, y: batch_y_test, keep_prob: 1.0})print(datetime.now().strftime(%c), step:, step, accuracy:, acc)# 准确率满足要求保存模型if acc acc_rate:model_path ./model/captcha.modelsaver.save(sess, model_path, global_stepstep)acc_rate 0.01if acc_rate 0.99: # 准确率达到99%则退出breakstep 1sess.close()if __name__ __main__:train()4、测试模型效果 # -*- coding:utf-8 -*- # name: model_test.pyimport tensorflow as tf from model_train import cnn_graph from captcha_gen import gen_captcha_text_and_image from util import vec2text, convert2gray from util import CAPTCHA_LIST, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, CAPTCHA_LEN from PIL import Imagedef captcha2text(image_list, heightCAPTCHA_HEIGHT, widthCAPTCHA_WIDTH):验证码图片转化为文本:param image_list::param height::param width::return:x tf.placeholder(tf.float32, [None, height * width])keep_prob tf.placeholder(tf.float32)y_conv cnn_graph(x, keep_prob, (height, width))saver tf.train.Saver()with tf.Session() as sess:saver.restore(sess, tf.train.latest_checkpoint(model/))predict tf.argmax(tf.reshape(y_conv, [-1, CAPTCHA_LEN, len(CAPTCHA_LIST)]), 2)vector_list sess.run(predict, feed_dict{x: image_list, keep_prob: 1})vector_list vector_list.tolist()text_list [vec2text(vector) for vector in vector_list]return text_listif __name__ __main__:text, image gen_captcha_text_and_image()img Image.fromarray(image)image convert2gray(image)image image.flatten() / 255pre_text captcha2text([image])print(验证码正确值:, text, 模型预测值:, pre_text)img.show()
http://www.lebaoying.cn/news/3289.html

相关文章:

  • 重庆网站设计网站手机网页如何做
  • 北京医院网站建设wordpress摘要设置
  • 天津专业智能建站工装设计方案网站
  • 做网站推广seo网络优化是什么意思
  • 山东省建设工程网站沧州网络运营中心电话
  • 怎么建立和设计网站wordpress伪静态win
  • 重庆的电子商务网站百度网站如何优化排名
  • 文化馆互联网站建设方案网站代维护
  • 怎样做企业网站一站式平台网站开发技术
  • 网上书城网站开发的结论与不足个旧做网站哪家公司好
  • 网站seo问题简单的介绍网站模板
  • 网站吸引人的功能网站用哪些系统做的比较好用
  • 网页设计与制作实用教程电子资源广州网站优化网站建设
  • 做网站公众号要多少钱做网站的公司 苏迪
  • 浙江建设信息港网站考试成绩查询番禺做网站开发
  • 做网站挣钱的人网站建设3a模型是什么
  • 设计网站要多久物流网站建设与管理规划书
  • 做网站设计用到的软件商丘网红宋飞
  • 做网站需要的设备仅仅建设银行网站打不开
  • 网站建设方案怎么做自己做设计图的app
  • 中国做的最好的网站河北保定网站建设
  • 网站 平台建设情况介绍app动效网站
  • 好企业网站电子商务网站
  • 济南黄河路桥建设集团官方网站百度容易收录哪些网站
  • wordpress拖动西安网站搜索引擎优化
  • 专业网站推荐淮北市官网
  • 企业网站设计注意自己做网站还能挣钱吗
  • 网站开发石家庄如何登录到wordpress
  • 上海响应式网站制作公司福建省建设职业注册资格管理中心网站
  • 网站图片一般多大讨论致同国际网站建设情况