[SciPy-User] array algorithm

Zachary Pincus zachary.pincus at yale.edu
Tue May 17 11:47:22 EDT 2011


> On Tue, May 17, 2011 at 7:13 AM, Wolfgang Kerzendorf <wkerzendorf at googlemail.com> wrote:
> 
> I'm wondering what is the most efficient way to implement an algorithm
> on a 2D-array:
> 
> If the array item is larger than the average of its four neighbours plus
> 3 times the sqrt of that average, set it to the average.
> 

weights = numpy.array([[0,0.25,0],[0.25,0,0.25],[0,0.25,0]])
average = scipy.ndimage.convolve(input.astype(float), weights)
threshold = average + 3*numpy.sqrt(average)
mask = input > threshold
input[mask] = average[mask]

Note that convolve has various boundary modes (reflect, constant, nearest, etc). Read the docstring.

Zach




More information about the SciPy-User mailing list