Skip to content

Instantly share code, notes, and snippets.

@marcodiiga
Created November 15, 2016 10:15
Show Gist options
  • Save marcodiiga/aa93c23e6b33b00e6d8a63ade32c2f8d to your computer and use it in GitHub Desktop.
Save marcodiiga/aa93c23e6b33b00e6d8a63ade32c2f8d to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
import numpy as np
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import re
# Set the radius to generate a C++-source-ready gaussian kernel in a multidimensional array
RADIUS = 6
def generate_gaussian_kernel(radius, sigma = 3, central_value = 3.5):
# Generate a size x size grid
a = np.linspace(-radius, radius, 2 * radius + 1)
b = a
x, y = np.meshgrid(a, b)
return x, y, np.exp(-(x / sigma)**2 - (y / sigma)**2) * central_value
xgrid, ygrid, mat = generate_gaussian_kernel(RADIUS)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xgrid, ygrid, mat, rstride=1, cstride=1, cmap='CMRmap')
plt.show()
# Pretty print for C++ inclusion
mat_str = '{\n'
for j in range(0, len(mat)):
row = mat[j]
mat_str += '{'
for i in range(0, len(row)):
value = row[i]
value_str = '{0:.16f}f'.format(value)
mat_str += value_str
if i != len(row) - 1:
mat_str += ', '
if j != len(mat) - 1:
mat_str += '},\n'
else:
mat_str += '}\n'
mat_str += '}'
str = '''#define KERNEL_RADIUS %d\n#define KERNEL_WIDTH %d\n#define KERNEL_HEIGHT %d\n
const float gaussian_kernel[KERNEL_HEIGHT][KERNEL_WIDTH] = \n%s;''' % (RADIUS, 2 * RADIUS + 1, 2 * RADIUS + 1, mat_str)
print str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment