[Numpy-discussion] avoiding loops when downsampling arrays

Moroney, Catherine M (388D) Catherine.M.Moroney@jpl.nasa....
Mon Feb 6 13:16:01 CST 2012


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!


More information about the NumPy-Discussion mailing list