[SciPy-User] downsampling with max in 2d

josef.pktd at gmail.com josef.pktd at gmail.com
Thu Feb 6 16:14:30 EST 2014


On Thu, Feb 6, 2014 at 3:54 PM, Dan Stowell <dan.stowell at eecs.qmul.ac.uk>wrote:

> Hi all,
>
> I would like to downsample 2D arrays using max-pooling. In other words,
> to downsample by a factor of 2 would reduce
>
>  a b c d
>  e f g h
>  i j k l
>  m n o p
>
> to
>
>  max(a,b,e,f) max(c,d,g,h)
>  max(i,j,m,n) max(k,l,o,p)
>
>
> I've searched through numpy and scipy and not found a method for this,
> but I'd be grateful for pointers if I've missed it.
> In the meantime, I wrote the following function. If you can spot a
> faster/better ways to achieve this, please do say:
>
>
> def maxdownsample2d(data, factor):
>         """Supply a 2D numpy array, and an integer factor by which to
> downsample (by nonoverlapping maxpooling) in both directions"""
>         # factor might not be exact fit, so we trim to this.
>         trimrows = int(np.floor(data.shape[0] / float(factor))) * factor
>         trimcols = int(np.floor(data.shape[1] / float(factor))) * factor
>         first = True
>         for coff in range(factor):
>                 for roff in range(factor):
>                         hopped = data[roff:trimrows:factor,
> coff:trimcols:factor]
>                         if first:
>                                 maxsofar = hopped
>                                 first = False
>                         else:
>                                 maxsofar = np.maximum(maxsofar, hopped)
>         return maxsofar
>
>
>
ndimage has a maximum filter and then slice, but it does a lot of redundant
calculation

I always wanted to use reduceat (and didn't find many opportunities)

>>> ar = np.random.randn(24,24)
>>> cut = np.arange(0, 24, 4)
>>> y1 = np.maximum.reduceat(ar, cut)
>>> y2 = np.maximum.reduceat(y1, cut,axis=1)

>>> y2 - maxdownsample2d(ar, 4)
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

Josef


>
> Best
> Dan
> --
> Dan Stowell
> Postdoctoral Research Assistant
> Centre for Digital Music
> Queen Mary, University of London
> Mile End Road, London E1 4NS
> http://c4dm.eecs.qmul.ac.uk/people/dans.htm
> http://www.mcld.co.uk/
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20140206/0698cc19/attachment.html>


More information about the SciPy-User mailing list