Last active
July 8, 2016 14:06
-
-
Save PolarNick239/e33935c564e17a3c354cf361c2d5278d to your computer and use it in GitHub Desktop.
2D Gaussian kernel coefficients calculating and plotting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
import numpy as np | |
from matplotlib import pyplot as plt | |
from matplotlib import cm | |
from mpl_toolkits.mplot3d import Axes3D | |
def makeGaussian(size, sigma=None): | |
if not isinstance(size, collections.Iterable): | |
size = (size, size) | |
w, h = size | |
if sigma is None: | |
sigma = 1.47 * min(w, h) / 6 | |
center = w / 2, h / 2 | |
x = np.arange(0, w, 1, np.float32) + 0.5 | |
y = np.arange(0, h, 1, np.float32) + 0.5 | |
y = y.reshape(-1, 1) | |
kernel = np.exp(-1/2 * ((x - center[0])**2 + (y - center[1])**2)/(sigma**2)) | |
kernel = kernel / (sigma * (2 * np.pi)**0.5) | |
kernel /= kernel.sum() | |
return kernel | |
def plot(kernel): | |
w, h = kernel.shape | |
w_offset, h_offset = (1 - w % 2) / 2, (1 - h % 2) / 2 | |
fig = plt.figure() | |
ax = fig.gca(projection='3d') | |
X = np.arange(-w/2 + w_offset, w/2 + w_offset, 1) | |
Y = np.arange(-h/2 + h_offset, h/2 + h_offset, 1) | |
X, Y = np.meshgrid(X, Y) | |
ax.plot_surface(X, Y, kernel, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) | |
size = 6 | |
kernel = makeGaussian(size) | |
print(kernel) | |
plot(kernel) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment