<kbd id='woaibaidu'></kbd><address id='woaibaidu'><style id='woaibaidu'></style></address><button id='woaibaidu'></button>

          当前位置:主页 > 脚本专栏 > python >
            python tensorflow学习之识别单张图片的实现的示例
            2018-02-12 22:07 发布 次浏览

          假定我们曾经装置好了tensorflow。

          普通在装置好tensorflow后,都市跑它的demo,而最多见的demo就是手写数字辨认的demo,也就是mnist数据集。

          但是我们仅仅是跑了它的demo而已,能够许多人会有和我1样的想法,假如拿来1张数字图片,如何使用我们训练的网络模子来辨认出来,上面我们就以mnist的demo来完成它。

          1.训练模子

          首先我们要训练好模子,而且把模子model.ckpt保管到指定文件夹

          saver = tf.train.Saver()   
          saver.save(sess, "model_data/model.ckpt") 

          将以上两行代码参加到训练的代码中,训练完成后保管模子便可,假如这局部有成绩,你可以百度查阅材料,tensorflow怎样保管训练模子,在这里我们就不罗嗦了。

          2.测试模子

          我们训练好模子后,将它保管在了model_data文件夹中,你会发现文件夹中呈现了4个文件

          然后,我们就能够对这个模子停止测试了,将待检测图片放在images文件夹下,履行

          # -*- coding:utf⑻ -*-  
          import cv2 
          import tensorflow as tf 
          import numpy as np 
          from sys import path 
          path.append('../..') 
          from common import extract_mnist 
           
          #初始化单个卷积核上的参数 
          def weight_variable(shape): 
            initial = tf.truncated_normal(shape, stddev=0.1) 
            return tf.Variable(initial) 
           
          #初始化单个卷积核上的偏置值 
          def bias_variable(shape): 
            initial = tf.constant(0.1, shape=shape) 
            return tf.Variable(initial) 
           
          #输出特点x,用卷积核W停止卷积运算,strides为卷积核挪动步长, 
          #padding表现能否需求补齐边沿像素使输入图象巨细稳定 
          def conv2d(x, W): 
            return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 
           
          #对x停止最大池化操作,ksize停止池化的规模, 
          def max_pool_2x2(x): 
            return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') 
           
           
          def main(): 
             
            #界说会话 
            sess = tf.InteractiveSession() 
             
            #声明输出图片数据,种别 
            x = tf.placeholder('float',[None,784]) 
            x_img = tf.reshape(x , [⑴,28,28,1]) 
           
            W_conv1 = weight_variable([5, 5, 1, 32]) 
            b_conv1 = bias_variable([32]) 
            W_conv2 = weight_variable([5,5,32,64]) 
            b_conv2 = bias_variable([64]) 
            W_fc1 = weight_variable([7*7*64,1024]) 
            b_fc1 = bias_variable([1024]) 
            W_fc2 = weight_variable([1024,10]) 
            b_fc2 = bias_variable([10]) 
           
            saver = tf.train.Saver(write_version=tf.train.SaverDef.V1)  
            saver.restore(sess , 'model_data/model.ckpt') 
           
            #停止卷积操作,并添加relu激活函数 
            h_conv1 = tf.nn.relu(conv2d(x_img,W_conv1) + b_conv1) 
            #停止最大池化 
            h_pool1 = max_pool_2x2(h_conv1) 
           
            #同理第2层卷积层 
            h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) 
            h_pool2 = max_pool_2x2(h_conv2) 
             
            #将卷积的产出展开 
            h_pool2_flat = tf.reshape(h_pool2,[⑴,7*7*64]) 
            #神经网络盘算,并添加relu激活函数 
            h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1) 
           
            #输入层,运用softmax停止多分类 
            y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2) 
           
            # mnist_data_set = extract_mnist.MnistDataSet('../../data/') 
            # x_img , y = mnist_data_set.next_train_batch(1) 
            im = cv2.imread('images/888.jpg',cv2.IMREAD_GRAYSCALE).astype(np.float32) 
            im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC) 
            #图片预处置 
            #img_gray = cv2.cvtColor(im , cv2.COLOR_BGR2GRAY).astype(np.float32) 
            #数据从0~255转为-0.5~0.5 
            img_gray = (im - (255 / 2.0)) / 255 
            #cv2.imshow('out',img_gray) 
            #cv2.waitKey(0) 
            x_img = np.reshape(img_gray , [⑴ , 784]) 
           
            print x_img 
            output = sess.run(y_conv , feed_dict = {x:x_img}) 
            print 'the y_con :  ', '\n',output 
            print 'the predict is : ', np.argmax(output) 
           
            #封闭会话 
            sess.close() 
           
          if __name__ == '__main__': 
            main() 
          
          

          ok,贴1下效果图

          输入:

          最初再贴1个cifar10的,觉得我的输出数据有点成绩,由于直接读cifar10的数据测试是没成绩的,可是换成本人的图片做预处置后输出后果就有成绩,(参考:cv2读入的数据是BGR顺序,PIL读入的数据是RGB顺序,cifar10的数据是RGB顺序),哪位童鞋能指出来记得留言通知我

          # -*- coding:utf⑻ -*-   
          from sys import path 
          import numpy as np 
          import tensorflow as tf 
          import time 
          import cv2 
          from PIL import Image 
          path.append('../..') 
          from common import extract_cifar10 
          from common import inspect_image 
           
           
          #初始化单个卷积核上的参数 
          def weight_variable(shape): 
            initial = tf.truncated_normal(shape, stddev=0.1) 
            return tf.Variable(initial) 
           
          #初始化单个卷积核上的偏置值 
          def bias_variable(shape): 
            initial = tf.constant(0.1, shape=shape) 
            return tf.Variable(initial) 
           
          #卷积操作 
          def conv2d(x, W): 
            return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 
           
           
           
          def main(): 
            #界说会话 
            sess = tf.InteractiveSession() 
             
            #声明输出图片数据,种别 
            x = tf.placeholder('float',[None,32,32,3]) 
            y_ = tf.placeholder('float',[None,10]) 
           
            #第1层卷积层 
            W_conv1 = weight_variable([5, 5, 3, 64]) 
            b_conv1 = bias_variable([64]) 
            #停止卷积操作,并添加relu激活函数 
            conv1 = tf.nn.relu(conv2d(x,W_conv1) + b_conv1) 
            # pool1 
            pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],padding='SAME', name='pool1') 
            # norm1 
            norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm1') 
           
           
            #第2层卷积层 
            W_conv2 = weight_variable([5,5,64,64]) 
            b_conv2 = bias_variable([64]) 
            conv2 = tf.nn.relu(conv2d(norm1,W_conv2) + b_conv2) 
            # norm2 
            norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,name='norm2') 
            # pool2 
            pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1],strides=[1, 2, 2, 1], padding='SAME', name='pool2') 
           
            #全衔接层 
            #权值参数 
            W_fc1 = weight_variable([8*8*64,384]) 
            #偏置值 
            b_fc1 = bias_variable([384]) 
            #将卷积的产出展开 
            pool2_flat = tf.reshape(pool2,[⑴,8*8*64]) 
            #神经网络盘算,并添加relu激活函数 
            fc1 = tf.nn.relu(tf.matmul(pool2_flat,W_fc1) + b_fc1) 
             
            #全衔接第2层 
            #权值参数 
            W_fc2 = weight_variable([384,192]) 
            #偏置值 
            b_fc2 = bias_variable([192]) 
            #神经网络盘算,并添加relu激活函数 
            fc2 = tf.nn.relu(tf.matmul(fc1,W_fc2) + b_fc2) 
           
           
            #输入层,运用softmax停止多分类 
            W_fc2 = weight_variable([192,10]) 
            b_fc2 = bias_variable([10]) 
            y_conv=tf.maximum(tf.nn.softmax(tf.matmul(fc2, W_fc2) + b_fc2),1e⑶0) 
           
            # 
            saver = tf.train.Saver() 
            saver.restore(sess , 'model_data/model.ckpt') 
            #input 
            im = Image.open('images/dog8.jpg') 
            im.show() 
            im = im.resize((32,32)) 
            # r , g , b = im.split() 
            # im = Image.merge("RGB" , (r,g,b)) 
            print im.size , im.mode 
           
            im = np.array(im).astype(np.float32) 
            im = np.reshape(im , [⑴,32*32*3]) 
            im = (im - (255 / 2.0)) / 255 
            batch_xs = np.reshape(im , [⑴,32,32,3]) 
            #print batch_xs 
            #获得cifar10数据 
            # cifar10_data_set = extract_cifar10.Cifar10DataSet('../../data/') 
            # batch_xs, batch_ys = cifar10_data_set.next_train_batch(1) 
            # print batch_ys 
            output = sess.run(y_conv , feed_dict={x:batch_xs}) 
            print output 
            print 'the out put is :' , np.argmax(output) 
            #封闭会话 
            sess.close() 
           
          if __name__ == '__main__': 
            main() 
          

          以上就是本文的全部内容,希望对各人的学习有所协助,也希望各人多多支持聚合网。