Reshaping OpenCV Image (numpy) Dimensions
<p>I need to convert an image in a numpy array loaded via cv2 into the correct format for the deep learning library mxnet for its convolutional layers.</p>

<p>My current images are shaped as follows: (256, 256, 3), or (height, width, channels).</p>

<p>From what I've been told, this actually needs to be (3, 256, 256), or (channels, height, width).</p>

<p>Unfortunately, my knowledge of numpy/python opencv isn't good enough to know how to manipulate the arrays correctly.</p>

<p>I've figured out that I could split the arrays into channels by cv2.split, but I'm uncertain of how to combine them again in the right format (I don't know if using cv2.split is optimal, or if there are better ways in numpy).</p>

<p>Thanks for any help.</p>

<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html" rel="nofollow"><code>numpy.rollaxis</code></a> as follow:
If your <code>image</code> as shape <code>(height, width, channels)</code></p>

<pre><code>import numpy as np

new_shaped_image = np.rollaxis(image, axis=2, start=0)
</code></pre>

<p>This means that the <code>2</code>nd axis of the <code>new_shaped_image</code> will be at <code>0</code> spot. </p>

<p>So <code>new_shaped_image.shape</code> will be <code>(channels, height, width)</code></p>

python opencv numpy mxnet