[SciPy-User] Focal Majority

Aronne Merrelli aronne.merrelli@gmail....
Tue Feb 21 12:58:56 CST 2012


On Mon, Feb 20, 2012 at 4:14 PM, Nyberg, Bjorn Johan <
bjorn.nyberg.10@aberdeen.ac.uk> wrote:

>  Hi Everyone,
> I have an interesting problem and I was hoping I could get some ideas
> here. I want to apply a focal majority within a moving 3 x 3 window whereby
> if there is a majority (any type of majority i.e. more than 5 cells having
> the same value), assign the center cell a value of 1 otherwise assign a
> value of 0. Now I realize in scipy and numpy there are options with
> convolutions methods but I am not entirely certain of how to apply a
> condition statement that I would require into the window calculations.
>
> Thanks
>  *Nyberg*
>
>

I don't think a convolution would work. A convolution is really just a
weighted sum, so I can't see a way to mimic a sort or conditional that way.

But, I think you can do this with scipy.ndimage.rank_filter. If you want 5
cells with the same value, it should be equivalent to checking if the first
and fifth ranked elements are the same (or second and sixth, etc...). So a
loop through the window size, combining rank_filter calls, should do this.
Definitely double check me on this - I'm not 100% sure it is doing the the
correct thing, and it probably isn't doing what you want at the edges. If
this is not fast enough, then I would consider writing a "brute force" loop
in Cython to make it fast.

In [90]: z
Out[90]:
array([[1, 1, 0, 8],
       [8, 1, 3, 1],
       [3, 1, 1, 2],
       [3, 1, 4, 5]])

In [91]: zmask = np.zeros(z.shape, bool)

In [92]: for n in range(4):
    zmask = np.logical_or(zmask, rank_filter(z,n,3)==rank_filter(z,(n-5),3))

In [93]: zmask
Out[93]:
array([[ True,  True, False, False],
       [ True,  True,  True, False],
       [False, False,  True, False],
       [ True, False, False, False]], dtype=bool)


HTH,
Aronne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20120221/5e9cbc98/attachment.html 


More information about the SciPy-User mailing list