Create a fast filter with a custom function on a numpy array

Viewed 45

I would like to implement a filter on numpy array which compute locally (given a footprint) the average distance to the central pixel. This function is similar to the local standard deviation, but takes the center pixel as the reference instead of the average.

One part of the problem is that my arrays are multimodal 2d images (rgb for example).

I have a full numpy implementation, that uses indexing tricks to perform the task, but it is limited to a 3x3 neighborhood for technical reasons.

I was thinking implementing this in cython, following this for example, but it seems not to work for vector images (with more than one value per pixel).

A numpy implementation (kind of pseudo code!) would look something like this:

img: np.ndarray  # source image of shape (n, m, 3) for example
mask: np.ndarray  # mask representing valid data (n, m)
footprint = disk(5)
n_px_nh = footprint.sum()
out = np.zeros(img.shape)
for i, neighborhood, masked_px in local_2d_filter(img, footprint, mask):
    # going through
    center_px = neighborhood[n_px_nh/2]  # works if n_px_nh is odd of course
    center_diff = 0
    for px in neighborhood[masked_px]:
        center_diff += ((px - center_px) ** 2).sum() ** 0.5  # distance to the center pixel
    center_diff /= n_px_nh
    out[i] = center_diff

local_2d_filter would be a function, like scipy.ndimage.generic_filter, which goes through an image, returning pixels in the footprint, around the center pixel .

Has anyone an idea on how to implement such filter ? Thanks

0 Answers
Related