1. 程式人生 > >tensorflow-影象邊緣+卷積+池化

tensorflow-影象邊緣+卷積+池化

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Oct  2 13:23:27 2018

@author: myhaspl
@email:[email protected]
tf.nn.conv2d+tf.nn.maxpool

"""

import tensorflow as tf
from PIL import Image    
import numpy as np

g=tf.Graph()

with g.as_default():

    def getImageData(fileNameList):
        imageData=[]
        for fn in fileNameList:        
            testImage = Image.open(fn).convert('L')   
            testImage.show() 
            imageData.append(np.array(testImage)[:,:,None])
        return np.array(imageData,dtype=np.float32)

    imageFn=("tractor.png",)
    imageData=getImageData(imageFn)
    testData=tf.constant(imageData)
    kernel=tf.constant(np.array(
            [
                   [[[0.]],[[1.]],[[0.]]],
                   [[[1.]],[[-4.]],[[1.]]], 
                   [[[0.]],[[1.]],[[0.]]]
            ])
            ,dtype=tf.float32)#3*3*1*1
    convData=tf.nn.conv2d(testData,kernel,strides=[1,1,1,1],padding="SAME")
    poolData=tf.nn.max_pool(convData,ksize=[1,2,2,1],strides=[1,1,1,1],padding='VALID')
    y1=tf.cast(convData, dtype=tf.int32)
    y2=tf.cast(poolData, dtype=tf.int32)
    init_op = tf.global_variables_initializer()
with tf.Session(graph=g) as sess:
    print testData.get_shape()
    print kernel.get_shape()
    resultData1=sess.run(y1)[0]
    resultData2=sess.run(y2)[0]
    resultData1=resultData1.reshape(resultData1.shape[0],resultData1.shape[1])
    resulImage1=Image.fromarray(np.uint8(resultData1),mode='L')   
    resulImage1.show()
    resultData2=resultData2.reshape(resultData2.shape[0],resultData2.shape[1])
    resulImage2=Image.fromarray(255-np.uint8(resultData2),mode='L')   
    resulImage2.show()
    print y1.get_shape()
中間那個圖是卷積,右邊那個圖是池化,自己對比一下,就明白池化的威力是很大的~
影象的卷積神經網路的操作流程就是:
CNN->DNN
DNN類似於普通神經網路,但屬於深度神經網路,而CNN則強調
下面的過程
卷積->池化->卷積-池化

tensorflow-影象邊緣+卷積+池化