[SciPy-User] How Can I Bin A Matrix?

josef.pktd@gmai... josef.pktd@gmai...
Thu Oct 29 09:55:06 CDT 2009


On Thu, Oct 29, 2009 at 10:47 AM, Tim Goodsall <tim.scipy@tropic.org.uk> wrote:
>  yo,
>
>
>  this works I think.  Not sure how fast it is on anything big.  and it
>  lops off some data if your binfactor is not a factor of the image
>  dimensions.  this might be a problem for you...  asymmetric binning
>  is more fun.
>
>  def spatiallybin(imap, binfactor):
>
>     lx,ly = imap.shape
>
>        # arbitrarily clip off some data if the dimensions not a multiple of
>        # the binning factor.
>        imap = imap[0:lx-(lx%binfactor)]
>        imap = imap[:,0:ly-ly%binfactor]
>
>        lx,ly = imap.shape
>
>        x,y = S.mgrid[0:lx:binfactor, 0:ly:binfactor]
>        x2,y2 = S.mgrid[0:lx/binfactor, 0:ly/binfactor]
>
>        # doubt this is the fastest way to do it for massive arrays.
>        new = S.array([imap[x+i,y+j] for i in range(binfactor) for j in range(binfactor)]).sum(0)
>
>     return new
>
>
>
>
>
>  On Thu, 2009-10-29 06:58, Joseph Smidt wrote:
>  > Hello,
>  >
>  >      Lets pretend I have some random 100x100 matrix and I wanted to
>  > form a 10x10 matrix where each element of the 10x10 matrix is the
>  > average of the corresponding 10x10  block of the 100x100 matrix.
>  >
>  >     To make this clearer, lets suppose I have a 4x4 matrix:
>  >
>  > ( 7, 2, 3, 4 )
>  > ( 9, 4, 5, 6 )
>  > ( 3, 5, 7, 9 )
>  > ( 1, 5, 2, 6 )
>  >
>  >     and lets say I want to bin it to a 2x2 matrix meaning I want to
>  > create a 2x2 matrix which would be:
>  >
>  > (  5.5, 4.5 )
>  > (  3.5, 6.0 )
>  >
>  > where 5.5 is the average of the upper left block of the 16x16 matrix:
>  >
>  > ( 7, 2 )
>  > ( 9, 4 )
>  >
>  >    and similarly with  the other elements.
>  >
>  >    Anyways, given an arbitrary NxN matrix is the an easy way to bin it
>  > to an MxM matrix where N is divisible by M?  If someone could come up
>  > with code to do this I would be very grateful.
>  >
>  >                   Joseph Smidt
>  >

I would try a full convolution with an average filter (scipy.signal or
scipy.ndimage ?)
 and then just select the right elements in the convoluted array.

Not tried.

Josef


>  > --
>  > ------------------------------------------------------------------------
>  > Joseph Smidt <josephsmidt@gmail.com>
>  >
>  > Physics and Astronomy
>  > 4129 Frederick Reines Hall
>  > Irvine, CA 92697-4575
>  > Office: 949-824-3269
>  > _______________________________________________
>  > SciPy-User mailing list
>  > SciPy-User@scipy.org
>  > http://mail.scipy.org/mailman/listinfo/scipy-user
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>


More information about the SciPy-User mailing list