[SciPy-User] Focal Majority
Tue Feb 21 12:58:56 CST 2012
On Mon, Feb 20, 2012 at 4:14 PM, Nyberg, Bjorn Johan <
> 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.
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 : z
array([[1, 1, 0, 8],
[8, 1, 3, 1],
[3, 1, 1, 2],
[3, 1, 4, 5]])
In : zmask = np.zeros(z.shape, bool)
In : for n in range(4):
zmask = np.logical_or(zmask, rank_filter(z,n,3)==rank_filter(z,(n-5),3))
In : zmask
array([[ True, True, False, False],
[ True, True, True, False],
[False, False, True, False],
[ True, False, False, False]], dtype=bool)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the SciPy-User