[Numpy-discussion] avoiding loops when downsampling arrays
Mon Feb 6 14:57:26 CST 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.
Sendt fra min iPad
Den 6. feb. 2012 kl. 20:16 skrev "Moroney, Catherine M (388D)" <Catherine.M.Moroney@jpl.nasa.gov>:
> 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/4, data_in.shape/4)
> found = numpy.zeros(shape_out).astype(numpy.bool)
> for i in xrange(0, shape_out):
> for j in xrange(0, shape_out):
> 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!
> NumPy-Discussion mailing list
More information about the NumPy-Discussion