theano中对图像进行convolution 运算

来源:互联网 发布:守望先锋伤害数据 12 编辑:程序博客网 时间:2024/06/05 18:14
(1) 定义计算过程中需要的symbolic expression

 1 """ 2 定义相关的symbolic experssion 3 """ 4 # convolution layer的输入,根据theano,它应该是一个4d tensor 5 input = T.tensor4(name='input') 6 # 共享权值W,它的shape为2,3,9,9 7 w_shp = (2,3,9,9);w_bound = numpy.sqrt(3*9*9) 8 W = theano.shared(numpy.asarray(rng.uniform(low= -1.0/w_bound, high = 1.0/w_bound,size=w_shp),dtype=input.dtype),name='W') 9 # 利用卷积核W对input进行卷积运算10 conv_out = conv.conv2d(input,W)11 # 偏执向量b12 b_shp = (2,)  # b是一个只有1个元素2的tuple13 b = theano.shared(numpy.asarray(rng.uniform(low= -.5, high = .5,size=b_shp),dtype=input.dtype),name='b')14 # 计算sigmoid函数15 output = T.nnet.sigmoid(conv_out+b.dimshuffle('x',0,'x','x'))16 # 输入输出function17 f = theano.function([input],output)

 

 

(2)利用真实数据计算

 1 """ 2 开始使用具体数值 3 """ 4 # 读入图像 5 img = Image.open('3wolfmoon.jpg', mode='r') 6 # 将输入图像存入在array中 7 img = numpy.array(img,dtype='float64')/256 8 # 对输入图像进行reshape 9 img_=img.transpose(2,0,1).reshape(1,3,639,516)10 # 利用convolution kernel对输入图像进行卷积运算11 filtered_img=f(img_)

(3)绘制需要显示的图像

 1 """ 2 绘制图像 3 """ 4 # 显示原始图像 5 pylab.subplot(1,3,1);pylab.axis('off');pylab.imshow(img);pylab.gray() 6 # 显示filter后的图像的channel1 7 pylab.subplot(1,3,2);pylab.axis('off');pylab.imshow(filtered_img[0,0,:,:]) 8 # 显示filter后的图像的channel2 9 pylab.subplot(1,3,3);pylab.axis('off');pylab.imshow(filtered_img[0,1,:,:])10 # 显示11 pylab.show()

 

整个代码段

 1 # -*- coding: utf-8 -*- 2  3 # 导入相关的模块 4 import theano 5 from theano import tensor as T 6 from theano.tensor.nnet import conv 7 import numpy 8 import pylab 9 from PIL import Image10 11 12 # 产生随机数的种子13 rng = numpy.random.RandomState(23455)14 15 """16 定义相关的symbolic experssion17 """18 # convolution layer的输入,根据theano,它应该是一个4d tensor19 input = T.tensor4(name='input')20 # 共享权值W,它的shape为2,3,9,921 w_shp = (2,3,9,9);w_bound = numpy.sqrt(3*9*9)22 W = theano.shared(numpy.asarray(rng.uniform(low= -1.0/w_bound, high = 1.0/w_bound,size=w_shp),dtype=input.dtype),name='W')23 # 利用卷积核W对input进行卷积运算24 conv_out = conv.conv2d(input,W)25 # 偏执向量b26 b_shp = (2,)  # b是一个只有1个元素2的tuple27 b = theano.shared(numpy.asarray(rng.uniform(low= -.5, high = .5,size=b_shp),dtype=input.dtype),name='b')28 # 计算sigmoid函数29 output = T.nnet.sigmoid(conv_out+b.dimshuffle('x',0,'x','x'))30 # 输入输出function31 f = theano.function([input],output)32 33 """34 开始使用具体数值35 """36 # 读入图像37 img = Image.open('3wolfmoon.jpg', mode='r')38 # 将输入图像存入在array中39 img = numpy.array(img,dtype='float64')/25640 # 对输入图像进行reshape41 img_=img.transpose(2,0,1).reshape(1,3,639,516)42 # 利用convolution kernel对输入图像进行卷积运算43 filtered_img=f(img_)44 45 """46 绘制图像47 """48 # 显示原始图像49 pylab.subplot(1,3,1);pylab.axis('off');pylab.imshow(img);pylab.gray()50 # 显示filter后的图像的channel151 pylab.subplot(1,3,2);pylab.axis('off');pylab.imshow(filtered_img[0,0,:,:])52 # 显示filter后的图像的channel253 pylab.subplot(1,3,3);pylab.axis('off');pylab.imshow(filtered_img[0,1,:,:])54 # 显示55 pylab.show()
View Code

 

0 0
原创粉丝点击