What is Julia's im2col?

The nice thing about Julia is that you can implement your own algorithm quite easily and it turns out to be also fast. Here is a very rough implementation of MATLAB’s im2col(A, [m,n]) in Julia:

julia> function im2col(A, m,n) # mxn: block_size
           M,N = size(A)
           mc = M-m+1          # no. vertical blocks
           nc = N-n+1          # no. horizontal blocks
           B = Array{eltype(A)}(undef, m*n, mc*nc)
           for j = 1:nc
             for i = 1:mc
               @views block = A[i:i+m-1, j:j+n-1]
               for k=1:m*n
                  B[k,(j-1)*mc+i] = block[k]
               end
             end
           end
           B
       end
im2col (generic function with 1 method)

julia> A = reshape(1:64,8,:) # A: 8x8
8×8 reshape(::UnitRange{Int64}, 8, 8) with eltype Int64:
 1   9  17  25  33  41  49  57
 2  10  18  26  34  42  50  58
 3  11  19  27  35  43  51  59
 4  12  20  28  36  44  52  60
 5  13  21  29  37  45  53  61
 6  14  22  30  38  46  54  62
 7  15  23  31  39  47  55  63
 8  16  24  32  40  48  56  64

julia> @btime B = im2col(A, 2,2)
  882.021 ns (1 allocation: 1.77 KiB)
4×49 Array{Int64,2}:
  1   2   3   4   5   6   7   9  10  11  12  13  14  15  …  41  42  43  44  45  46  47  49  50  51  52  53  54  55
  2   3   4   5   6   7   8  10  11  12  13  14  15  16     42  43  44  45  46  47  48  50  51  52  53  54  55  56
  9  10  11  12  13  14  15  17  18  19  20  21  22  23     49  50  51  52  53  54  55  57  58  59  60  61  62  63
 10  11  12  13  14  15  16  18  19  20  21  22  23  24     50  51  52  53  54  55  56  58  59  60  61  62  63  64
2 Likes