-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConvolution.py
More file actions
67 lines (48 loc) · 1.58 KB
/
Convolution.py
File metadata and controls
67 lines (48 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# http://github.com/timestocome
# adapted from https://github.com/lisa-lab/DeepLearningTutorials
import numpy as np
import theano
from theano import tensor as T
from theano.tensor.nnet import conv
import pylab
from PIL import Image
# init
rng = np.random.RandomState(27)
input = T.tensor4(name='input')
height = width = 512 # image size
w_shape = (2, 3, 9, 9) # filters, image depth, filter_height, filter_width
w_bound = np.sqrt(3 * 9 * 9) # depth, height, width
# randomly init weights should act as an edge detector
W = theano.shared(np.asarray(rng.uniform(
low = -1./w_bound,
high = 1./w_bound,
size = w_shape), dtype=input.dtype), name = 'W')
# 2 filter maps so two bias weights are required
b_shape = (2,)
b = theano.shared(np.asarray(rng.uniform(
low = -.5, high = .5, size=b_shape),
dtype = input.dtype), name = 'b')
# convolvute the image
conv_out = conv.conv2d(input, W)
# dimshuffle reshapes the tensor
output = T.nnet.sigmoid(conv_out + b.dimshuffle('x', 0, 'x', 'x'))
# create funtions
f = theano.function([input], output)
# open an image
image = Image.open('kitten.jpg')
image = np.asarray(image, dtype='float64') / 256
# convert to 4d array
image_ = image.transpose(2, 0, 1).reshape(1, 3, height, width)
filtered_image = f(image_)
# plot original, first and second outputs
pylab.subplot(1, 3, 1)
pylab.axis('off')
pylab.imshow(image)
pylab.gray()
pylab.subplot(1, 3, 2)
pylab.axis('off')
pylab.imshow(filtered_image[0, 0, :, :])
pylab.subplot(1, 3, 3)
pylab.axis('off')
pylab.imshow(filtered_image[0, 1, :, :])
pylab.show()