Skip to content

Instantly share code, notes, and snippets.

@matsuken92
Last active August 29, 2015 14:24
Show Gist options
  • Save matsuken92/a8d47af7b761e0e473dc to your computer and use it in GitHub Desktop.
Save matsuken92/a8d47af7b761e0e473dc to your computer and use it in GitHub Desktop.
Gabor Filter
# (reference) https://ja.wikipedia.org/wiki/ガボールフィルタ
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import math
plt.style.use('fivethirtyeight')
def gabor_filter(sigma_x, sigma_y, theta, lamb, psi, gamma):
sz_x = math.floor(6 * sigma_x)
if (sz_x % 2) == 0:
sz_x = sz_x + 1
sz_y = math.floor(6 * sigma_y)
if (sz_y %2)==0:
sz_y=sz_y+1
xx = np.linspace(-math.floor(sz_x/2), math.floor(sz_x/2), 100)
yy = np.linspace(math.floor(-sz_y/2), math.floor(sz_y/2), 100)
X, Y = np.meshgrid(xx, yy)
# Rotation
x_theta = X*np.cos(theta) + Y*np.sin(theta)
y_theta = -X*np.sin(theta) + Y*np.cos(theta)
x_theta2 = np.array(map(lambda x : x**2 / sigma_x**2, x_theta))
x_theta3 = np.array(map(lambda x : 2*np.pi/lamb*x + psi, x_theta))
y_theta2 = np.array(map(lambda y : gamma**2 * y**2 / sigma_y**2, y_theta))
return np.exp(-.5*(x_theta2 + y_theta2))*np.cos(x_theta3)
def draw_digit(data, size):
#print n
#size = 17
Z = data.reshape(size,size) # convert from vector to 28x28 matrix
Z = np.array(Z[::-1,:]).T # flip vertical
plt.xlim(0,size-1)
plt.ylim(0,size-1)
plt.pcolor(Z)
plt.gray()
plt.tick_params(labelbottom="off")
plt.tick_params(labelleft="off")
#\lambda は波長のコサイン成分、\theta はガボール関数の縞模様の方向、\psi は位相オフセット、\gamma は空間アスペクト比
data = gabor_filter(90., 90., theta=np.pi/4, lamb=400, psi=0., gamma=.5)
plt.figure(figsize=(3,3))
draw_digit(data, data.shape[0])
def cos_filter(size, theta=0, freq=1, phase=0):
if (size %2) != 0:
tuning = 0.5
else:
tuning = 0
_min = size - math.floor(size/2) - tuning
_max = size + math.floor(size/2) + tuning
xx = np.linspace(_min, _max, size)
yy = np.linspace(_min, _max, size)
X, Y = np.meshgrid(xx, yy)
# Rotation
x_theta = (X*freq+phase)*np.cos(theta) + (Y*freq+phase)*np.sin(theta)
return np.cos(x_theta)
data = cos_filter(17, theta=np.pi/4, freq=.346, phase=-1.5)
plt.figure(figsize=(3,3))
draw_digit(data, data.shape[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment