Skip to content
Advertisement

Implement MATLAB’s im2col ‘sliding’ in Python

Q: How to speed this up?

Below is my implementation of Matlab’s im2col ‘sliding’ with the additional feature of returning every n’th column. The function takes an image (or any 2 dim array) and slides from left to right, top to bottom, picking off every overlapping sub-image of a given size, and returning an array whose columns are the sub-images.

JavaScript

example:

JavaScript

returns:

JavaScript

The performance isn’t great, especially considering whether I call im2col_sliding(big_matrix, (8, 8)) (62001 columns) or im2col_sliding(big_matrix, (8, 8), 10) (6201 columns; keeping only every 10th vector) it will take the same amount of time [where big_matrix is of size 256 x 256].

I’m looking for any ideas to speed this up.

Advertisement

Answer

Approach #1

We could use some broadcasting here to get all the indices of all those sliding windows in one go and thus with indexing achieve a vectorized solution. This is inspired by Efficient Implementation of im2col and col2im.

Here’s the implementation –

JavaScript

Approach #2

Using newly gained knowledge of NumPy array strides that lets us create such sliding windows, we would have another efficient solution –

JavaScript

Approach #3

The strided method listed in the previous approach has been incorporated into scikit-image module for a less messier, like so –

JavaScript

Sample runs –

JavaScript

Runtime test

JavaScript

Around 16x speedup there with the strided method over the original loopy version!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement