Sometimes in image processing you'd like to work with an image in tiles, in square blocks of pixels I mean. The tiles can be used for vector quantization, for example. You can split the image with a simple loop like this:
Unfortunately it gets slow for large images. Fortunately it's possible to do the same thing 1000x faster with some array reshaping trickery. The code below is also 15x faster than scikit-image's view_as_blocks function that does the same thing.
We can also make vectors of the tiles. This is useful for analysis such as clustering where you don't care about the spatial relationships between the pixels of a tile.
I was actually surprised to see a speed difference this large :) Allocating the tiles array outside the naive function had roughly the same speed as the code above. The scikit-image implementation uses np.stride_tricks.as_strided which for some reason is clearly slower than just the reshape + transpose trick we do here.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: