Convert image into 4x4 non-overlapping blocks
<p>I want to divide an image into 4x4 non-overlapping blocks in python and then convert that block into array of 16 element.</p>

<p>I recommend using a quality-library like <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a>, especially if there are more steps needed in the future. It is based on numpy/scipy.</p>

<p>A kind of minimal example (<a href="http://scikit-image.org/docs/dev/auto_examples/numpy_operations/plot_view_as_blocks.html?highlight=block" rel="nofollow">from the docs</a>) would be the following.</p>

<h3>Code:</h3>

<pre><code>from skimage import data
from skimage import color
from skimage.util import view_as_blocks

# get astronaut from skimage.data in grayscale
l = color.rgb2gray(data.astronaut())

# size of blocks
block_shape = (4, 4)

# see astronaut as a matrix of blocks (of shape block_shape)
view = view_as_blocks(l, block_shape)

# collapse the last two dimensions in one
flatten_view = view.reshape(view.shape[0], view.shape[1], -1)

print(flatten_view.shape)
</code></pre>

<h3>Output</h3>

<pre><code>(128, 128, 16)  # 128x128 blocks a 16 elements each
</code></pre>

python image-processing