How do I median bin a 2D image in python?
<p>I have a 2D numarray, of size WIDTHxHEIGHT. I would like to bin the array by finding the median of each bin so that the resultant array is WIDTH/binsize x HEIGHT/binsize. Assume that both WIDTH and HEIGHT are divisible by binsize. </p>

<p>I have found solutions where the binned array values are the sum or average of the individual elements in each bin: 
<a href="http://stackoverflow.com/questions/36063658/how-to-bin-a-2d-array-in-numpy">How to bin a 2D array in numpy?</a></p>

<p>However, if I want to do a median combine of elements in each bin, I haven't been able to figure out a solution. Your help would be much appreciated!</p>

<p>Is this what you are looking for? </p>

<pre><code>import numpy as np
a = np.arange(24).reshape(4,6)

def median_binner(a,bin_x,bin_y):
    m,n = np.shape(a)
    return np.array([np.median(col) for row in a.reshape(bin_x,bin_y,m//bin_x,n//bin_y) for col in row]).reshape(bin_x,bin_y)



print "Original Matrix:"
print a
print "\n"
bin_tester1 = median_binner(a,2,3)
print "2x3 median bin :"
print bin_tester1
print "\n"
bin_tester2 = median_binner(a,2,2)
print "2x2 median bin :"
print bin_tester2
</code></pre>

<p>result: </p>

<pre><code>Original Matrix:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]


2x3 median bin :
[[  1.5   5.5   9.5]
 [ 13.5  17.5  21.5]]


2x2 median bin :
[[  2.5   8.5]
 [ 14.5  20.5]]
</code></pre>

python arrays numpy