forked from lazyprogrammer/machine_learning_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_blur.py
103 lines (87 loc) · 2.68 KB
/
custom_blur.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# https://deeplearningcourses.com/c/deep-learning-convolutional-neural-networks-theano-tensorflow
# https://udemy.com/deep-learning-convolutional-neural-networks-theano-tensorflow
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
# from scipy.signal import convolve2d
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from datetime import datetime
# def convolve2d(X, W):
# t0 = datetime.now()
# n1, n2 = X.shape
# m1, m2 = W.shape
# Y = np.zeros((n1 + m1 - 1, n2 + m2 - 1))
# for i in xrange(n1 + m1 - 1):
# for ii in xrange(m1):
# for j in xrange(n2 + m2 - 1):
# for jj in xrange(m2):
# if i >= ii and j >= jj and i - ii < n1 and j - jj < n2:
# Y[i,j] += W[ii,jj]*X[i - ii,j - jj]
# print "elapsed time:", (datetime.now() - t0)
# return Y
# def convolve2d(X, W):
# t0 = datetime.now()
# n1, n2 = X.shape
# m1, m2 = W.shape
# Y = np.zeros((n1 + m1 - 1, n2 + m2 - 1))
# for i in xrange(n1):
# for j in xrange(n2):
# Y[i:i+m1,j:j+m2] += X[i,j]*W
# print "elapsed time:", (datetime.now() - t0)
# return Y
# same size as input
def convolve2d(X, W):
n1, n2 = X.shape
m1, m2 = W.shape
Y = np.zeros((n1 + m1 - 1, n2 + m2 - 1))
for i in range(n1):
for j in range(n2):
Y[i:i+m1,j:j+m2] += X[i,j]*W
ret = Y[m1//2:-m1//2+1,m2//2:-m2//2+1]
assert(ret.shape == X.shape)
return ret
# smaller than input
# def convolve2d(X, W):
# n1, n2 = X.shape
# m1, m2 = W.shape
# Y = np.zeros((n1 + m1 - 1, n2 + m2 - 1))
# for i in xrange(n1):
# for j in xrange(n2):
# Y[i:i+m1,j:j+m2] += X[i,j]*W
# ret = Y[m1-1:-m1+1,m2-1:-m2+1]
# return ret
# load the famous Lena image
img = mpimg.imread('lena.png')
# what does it look like?
plt.imshow(img)
plt.show()
# make it B&W
bw = img.mean(axis=2)
plt.imshow(bw, cmap='gray')
plt.show()
# create a Gaussian filter
W = np.zeros((20, 20))
for i in range(20):
for j in range(20):
dist = (i - 9.5)**2 + (j - 9.5)**2
W[i, j] = np.exp(-dist / 50.)
# let's see what the filter looks like
plt.imshow(W, cmap='gray')
plt.show()
# now the convolution
out = convolve2d(bw, W)
plt.imshow(out, cmap='gray')
plt.show()
# what's that weird black stuff on the edges? let's check the size of output
print(out.shape)
# after convolution, the output signal is N1 + N2 - 1
# try it in color
out = np.zeros(img.shape)
W /= W.sum()
for i in range(3):
out[:,:,i] = convolve2d(img[:,:,i], W)
plt.imshow(out)
plt.show()