How to apply a disc shaped mask to a NumPy array?
I would do it like this, where (a, b) is the center of your mask:
import numpy as np
a, b = 1, 1
n = 7
r = 3
y,x = np.ogrid[-a:n-a, -b:n-b]
mask = x*x + y*y <= r*r
array = np.ones((n, n))
array[mask] = 255
I just wanted to share with everyone a slightly more advanced application of this technique that I just had to face.
My problem was to apply this circular kernel to compute the mean of all the values surrounding each point in a 2D matrix. The kernel generated can be passed to scipy's generic filter in the following way:
import numpy as np
from scipy.ndimage.filters import generic_filter as gf
kernel = np.zeros((2*radius+1, 2*radius+1))
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
mask = x**2 + y**2 <= radius**2
kernel[mask] = 1
circular_mean = gf(data, np.mean, footprint=kernel)
Hope this helps!