Skip to content Skip to sidebar Skip to footer

Calculating Windowed Probabilities In Numpy/scipy

I'm trying to do a bit of (I think) an obscure filter on an image using numpy/scipy. What I want is essentially a windowed probability distribution. I start with a grayscale image.

Solution 1:

Interesting math problem and seems like there would be a simple solution with Scikit-image's view_as_windows to get (3,3) sliding windows and then comparing against the center pixel for getting the count of its occurrence in its window and finally dividing by the kernel size of 9.

Hence, the implementation for an image a would be -

from skimage.util.shape import view_as_windows

(view_as_windows(a,(3,3)) == a[1:-1,1:-1,None,None]).sum((-2,-1))/9.0

This gets us the results for the non-boundary elements. To cover for all the elements, we can pad the image with an invalid specifier, say -1 around it and then use the proposed method.

Sample run -

In [61]: a
Out[61]: 
array([[  1,   0,   0,   0,   3,   4],
       [  2,   0,   0,   0,   6,   0],
       [  4, 255, 255, 255,   8,   2],
       [  0,   5,   0,   5,   6,   2]])

In [76]: (view_as_windows(a,(3,3)) == a[1:-1,1:-1,None,None]).sum((-2,-1))/9.0
Out[76]: 
array([[ 0.44,  0.67,  0.44,  0.11],
       [ 0.22,  0.33,  0.22,  0.11]])

To cover for all elements -

In [74]: a1 = np.pad(a, (1,1), 'constant', constant_values=(-1, -1))

In [75]: (view_as_windows(a1,(3,3)) == a1[1:-1,1:-1,None,None]).sum((-2,-1))/9.0
Out[75]: 
array([[ 0.11,  0.44,  0.67,  0.44,  0.11,  0.11],
       [ 0.11,  0.44,  0.67,  0.44,  0.11,  0.11],
       [ 0.11,  0.22,  0.33,  0.22,  0.11,  0.22],
       [ 0.11,  0.11,  0.11,  0.11,  0.11,  0.22]])

Post a Comment for "Calculating Windowed Probabilities In Numpy/scipy"