col2im的实现，这是im2col的逆过程

im2col的原理网上一大把，我懒得写了。

# 2. 矩阵展开

1 2 3
4 5 6
7 8 9


1 4 7 2 5 8 3 6 9


# 5. 实现代码

mat im2col(field<mat> input_data, int filter_h, int filter_w, int stride, int pad)
{
int N, C, H, W;
N = input_data.n_rows;
C = input_data.n_cols;
H = input_data(0, 0).n_rows;
W = input_data(0, 0).n_cols;
int out_h = (H + 2 * pad - filter_h) / stride + 1;
int out_w = (W + 2 * pad - filter_w) / stride + 1;
field<mat> img = input_data;
mat col(out_h * out_w * N, C * filter_h * filter_w, fill::zeros);
for (int n = 0, z = 0; n < N; n++)
{
for (int i = 0; i < out_h; i++)
{
for (int j = 0; j < out_w; j++, z++)
{
for (int k = 0; k < C; k++)
{
mat filter(filter_h, filter_w, fill::zeros);
filter = img(n, k)(span(i * stride, i * stride + filter_h - 1), span(j * stride, j * stride + filter_w - 1));
filter.reshape(1, filter_h * filter_w);
int x = z;
int y0 = filter_h * filter_w * k;
int y1 = filter_h * filter_w * k + filter_h * filter_w - 1;
col(span(x, x), span(y0, y1)) = filter;
}
}
}
}
return col;
}


posted @ 2021-05-23 12:22  c艹用户  阅读(106)  评论(0编辑  收藏  举报