Commit 80716ed0 authored by Taddeüs Kroes's avatar Taddeüs Kroes

improc ass4: Added samples, Gaussian filter and timer.

parent 6f95700e
#!/usr/bin/env python
from numpy import zeros, arange, pi, e, ceil, meshgrid
from matplotlib.pyplot import imread, imshow, plot, xlabel, ylabel, show, \
subplot, xlim, savefig
from mpl_toolkits.mplot3d import Axes3D
from scipy.ndimage import convolve
from time import time
from sys import argv, exit
def Gauss(s):
"""Create a sampled Gaussian function of scale s."""
size = int(ceil(3 * s))
W = zeros((2 * size + 1, 2 * size + 1))
t = s ** 2
a = 1 / (2 * pi * t)
# Sample the Gaussian function
for x in xrange(-size, size + 1):
for y in xrange(-size, size + 1):
W[x, y] = a * e ** -((x ** 2 + y ** 2) / (2 * t))
# Make sure that the sum of all kernel values is equal to one
return W / W.sum()
def plot_diff(F, s):
"""Calculate and plot the convolution of scale s of an image F."""
W = Gauss(s)
G = convolve(F, W, mode='nearest')
# Original image
subplot(131)
imshow(F, cmap='gray')
# Gauss function
x = arange(W.shape[0])
X, Y = meshgrid(x, x)
ax = subplot(132, projection='3d')
ax.plot_surface(X, Y, W, rstride=1, cstride=1, cmap='jet')
ax.set_zlim3d(0, 1)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('g(x, y)')
# Convolution
subplot(133)
imshow(G, cmap='gray')
show()
def exit_usage():
print 'Usage: python %s timer [ FILE ] | diff [ SCALE ]' % argv[0]
exit(1)
if len(argv) < 1:
exit_with_usage()
F = imread('cameraman.png')
if argv[1] == 'timer':
# Time for multiple scales
S = [1, 2, 3, 5, 7, 9, 11, 15, 19]
repeat = 1
timings = []
for i, s in enumerate(S):
t = 0
for k in xrange(repeat):
W = Gauss(s)
start = time()
convolve(F, W, mode='nearest')
t += time() - start
timings.append(t / repeat)
xlim(S[0], S[-1])
xlabel('s')
ylabel('time (s)')
plot(S, timings, 'o-')
if len(argv) > 2:
savefig(argv[2])
show()
elif argv[1] == 'diff':
if len(argv) < 2:
exit_with_usage()
plot_diff(F, int(argv[2]))
#!/usr/bin/env python
from numpy import arange, meshgrid, pi, sin, cos
from matplotlib.pyplot import subplot, imshow, show, quiver
# Create sample axes
x = arange(-100, 101)
y = arange(-100, 101)
xx = arange(-100, 101, 10)
yy = arange(-100, 101, 10)
Y, X = meshgrid(x, y)
YY, XX = meshgrid(yy, xx)
# Configure constants
A = 1
B = 2
V = 6 * pi / 201
W = 4 * pi / 201
# Create sample data
F = A * sin(V * X) + B * cos(W * Y)
Fx = A * V * cos(V * X)
Fy = -B * W * sin(W * Y)
FFx = -A * V ** 2 * sin(V * XX)
FFy = -B * W ** 2 * cos(W * YY)
# Plot F, Fx and Fy sample data next to each other
# Show FFx and FFy as a quiver plot over F
subplot(131)
imshow(F, cmap='gray', extent=(-100, 100) * 2)
quiver(yy, xx, FFy, -FFx, color='red')
subplot(132)
imshow(Fx, cmap='gray')
subplot(133)
imshow(Fy, cmap='gray')
show()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment