[Numpy-discussion] avoiding loops when downsampling arrays

Sturla Molden sturla at molden.no
Mon Feb 6 15:57:26 EST 2012


Short answer: Create 16 view arrays, each with a stride of 4 in both dimensions. Test them against the conditions and combine the tests with an |= operator. Thus you replace the nested loop with one that has only 16 iterations. Or reshape to 3 dimensions, the last with length 4, and you can do the same with only four view arrays.

Sturla

Sendt fra min iPad

Den 6. feb. 2012 kl. 20:16 skrev "Moroney, Catherine M (388D)" <Catherine.M.Moroney at jpl.nasa.gov>:

> Hello,
> 
> I have to write a code to downsample an array in a specific way, and I am hoping that
> somebody can tell me how to do this without the nested do-loops.  Here is the problem
> statement:  Segment a (MXN) array into 4x4 squares and set a flag if any of the pixels
> in that 4x4 square meet a certain condition.
> 
> Here is the code that I want to rewrite avoiding loops:
> 
> shape_out = (data_in.shape[0]/4, data_in.shape[1]/4)
> found = numpy.zeros(shape_out).astype(numpy.bool)
> 
> for i in xrange(0, shape_out[0]):
>    for j in xrange(0, shape_out[1]):
> 
>        excerpt = data_in[i*4:(i+1)*4, j*4:(j+1)*4]
>        mask = numpy.where( (excerpt >= t1) & (excerpt <= t2), True, False)
>        if (numpy.any(mask)):
>            found[i,j] = True
> 
> Thank you for any hints and education!
> 
> Catherine
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion



More information about the NumPy-Discussion mailing list