# [SciPy-User] down-sampling an array by averaging - vectorized form?

jkhilmer@chemistry.montan... jkhilmer@chemistry.montan...
Sat Feb 11 00:08:08 CST 2012

```Andrew,

This is a very naive response, since I don't have nearly the
experience as many of the other contributors here.

Since you're working with images, and you might want more complicated
variants of this process in the future, why not convolve your array
and slice the output with a stride/step.  For the sizes you're talking
about, memory shouldn't be a concern.  That should give you a very
flexible procedure that is inherently "vectorized".

Jonathan

On Fri, Feb 10, 2012 at 8:19 PM, andrew giessel
<andrew.giessel@gmail.com> wrote:
> Hello all,
>
> I'm looking to down-sample an image by averaging.  I quickly hacked up the
> following code, which does exactly what I want, but the double loop is slow
> (the images I'm working with are ~2000x2000 pixels).  Is there a nice way to
> vectorize this?  A quick profile showed that most of the time is spend
> averaging- perhaps there is a way to utilize np.sum or np.cumsum, divide the
> whole array, and then take every so many pixels?
>
> This method of down-sampling (spatial averaging) makes sense for the type of
> data I'm using and yields good results, but I'm also open to alternatives.
>
> Andrew
>
> ######################
> import numpy as np
>
> def downsample(array, reduction):
>     """example call for 2fold size reduction:  newImage = downsample(image,
> 2)"""
>
>     newArray = np.empty(array.shape[0]/reduction, array.shape[1]/reduction)
>
>     for x in range(newArray.shape[0]):
>         for y in range(newArray.shape[1]):
>             newArray[x,y] =
> np.mean(array[x*reduction:((x+1)*reduction)-1, y*reduction:((y+1)*reduction)-1])
>
>     return newArray
> ######################
>
> --
> Andrew Giessel, PhD
>
> Department of Neurobiology, Harvard Medical School
> 220 Longwood Ave Boston, MA 02115
> ph: 617.432.7971 email: andrew_giessel@hms.harvard.edu
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
```