Post date: Oct 09, 2015 3:6:45 AM
im2col is a popular function in Matlab that maps patches in a matrix or in this case an image (im) to (2) columns (col) in a newly formed matrix. I was recently experimenting with C++ implementations of this function and used the following code.
MatrixXf im2col2(MatrixXf& src, int rowblock, int colblock, int rowslide, int colslide)
{
int m = src.rows();
int n = src.cols();
int rowB = floor((m - rowblock) / rowslide) + 1;
int colB = floor((n - colblock) / colslide) + 1;
int dstrows = ((m - rowblock) % rowslide != 0 ? rowB + 1 : rowB);
int dstcols = ((n - colblock) % colslide != 0 ? colB + 1 : colB);
MatrixXf dst(rowblock*colblock, dstrows*dstcols);
int colIndex = 0;
int rowOffset;
bool colbreak = false;
bool rowbreak;
int j = 0;
int i;
while (!colbreak) // Col iterator
{
if (j + colblock > n - 1)
{
j = n - colblock;
colbreak = true;
}
rowbreak = false;
i = 0;
while (!rowbreak) // Row iterator
{
if (i + rowblock > m - 1)
{
i = m - rowblock;
rowbreak = true;
}
rowOffset = 0;
for (int jj = 0; jj < colblock; jj++) // col iterator of sub-block
{
for (int ii = 0; ii < rowblock; ii++) // row iterator of sub-block
{
dst(jj * rowblock + ii, colIndex) = src(i + ii, j + jj);
}
}
colIndex += 1;
i += rowslide;
}
j += colslide;
}
return dst;
}
With a 100x100 test matrix, this code clocked in at 83ms..
I changed the Eigen MatrixXf to OpenCV Mat's and clocked 20ms..
Incidentally, i had previously tried using Eigen's Matrix block functions in place of the ii loop. The readings were in the region of 200ms..