Align image columns by max value
<p>I have an image where I would like to offset each column so that the maximum value of each column is vertically centered in the image. Here's some toy data:</p>

<pre><code>unaligned = np.array([[0,0,1,2,3,2,1,0,0,0],
                      [0,0,0,1,2,3,2,1,0,0],
                      [0,1,2,3,4,3,2,1,0,0],
                      [0,0,1,2,3,2,1,0,0,0],
                      [0,0,0,1,2,3,2,1,0,0]]).T
</code></pre>

<p><a href="https://i.stack.imgur.com/KAHi9.png" rel="nofollow"><img src="https://i.stack.imgur.com/KAHi9.png" alt="enter image description here"></a></p>

<p>Once aligned, it should look like</p>

<pre><code>aligned = np.array([[0,0,0,1,2,3,2,1,0,0],
                    [0,0,0,1,2,3,2,1,0,0],
                    [0,0,1,2,3,4,3,2,1,0],
                    [0,0,0,1,2,3,2,1,0,0],
                    [0,0,0,1,2,3,2,1,0,0]]).T
</code></pre>

<p><a href="https://i.stack.imgur.com/Y568F.png" rel="nofollow"><img src="https://i.stack.imgur.com/Y568F.png" alt="enter image description here"></a></p>

<p>I could go column by column, find the index of the maximum value, then rewrite the column to a new array with the maximum value at the midpoint. But is there a concise (and faster) way to do this, especially if I have images with thousands of columns? Perhaps even some image processing routine with the column max values used as control points?</p>

<p>Thanks!</p>

<p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>

<pre><code>m,n = unaligned.shape
col_shifts = m//2 - unaligned.argmax(0)
row_idx = np.mod(np.arange(m)[:,None]-col_shifts,m)
aligned_out = unaligned[row_idx,np.arange(n)]
</code></pre>

<p>If you are trying to fill the shifted in positions with zeros and the ends of the columns are zeros, we can alternatively get <code>row_idx</code> with <code>clipping</code>, like so -</p>

<pre><code>row_idx = (np.arange(m)[:,None]-col_shifts).clip(min=0,max=m-1)
</code></pre>

python numpy image-processing