Function File: im2col (A, block_size)
Function File: im2col (A, block_size, block_type)
Function File: im2col (A, "indexed", …)

Rearrange blocks from matrix into columns.

Rearranges blocks of size block_size, sampled from the matrix A, into a serie of columns. This effectively transforms any image into a 2 dimensional matrix, a block per column, which can then be passed to other functions that perform calculations along columns.

Both blocks and matrix A can have any number of dimensions (though for sliding blocks, a block can’t be larger than A in any dimension). Blocks are always accessed in column-major order (like Octave arrays are stored) so that a matrix can be easily reconstructed with reshape and col2im. For a 2 dimensional matrix, blocks are taken first from the top to the bottom, and then from the left to the right of the matrix.

The sampling can be performed in two different ways as defined by block_type (defaults to "sliding"):

"distinct"

Each block is completely distinct from the other, with no overlapping elements. The matrix A is padded as required with a value of 0 (or 1 for non-integer indexed images).

"sliding"

A single block slides across A without any padding.

While this can be used to perform sliding window operations such as maximum and median filters, specialized functions such as imdilate and medfilt2 will be more efficient.

Note that large images being arranged in large blocks can easily exceed the maximum matrix size (see sizemax). For example, a matrix A of size 500x500, with sliding block of size [100 100], would require a matrix with 2.4108e+09 elements, i.e., the number of elements in a block, 100*100, times the number of blocks, (500-10+1) * (500-10+1).

If A is an indexed image, the second argument should be the string "indexed" so that any required padding is done correctly. The padding value will be 0 except for indexed images of class uint8 and uint16.

See also: blockproc, bestblk, col2im, colfilt, nlfilter, reshape.

Demonstration 1

The following code

 ## Divide A using distinct blocks and then reverse the operation
 A = [ 1:10
      11:20
      21:30
      31:40];
 B = im2col (A, [2 5], "distinct")
 C = col2im (B, [2 5], [4 10], "distinct")

Produces the following output

B =

    1   21    6   26
   11   31   16   36
    2   22    7   27
   12   32   17   37
    3   23    8   28
   13   33   18   38
    4   24    9   29
   14   34   19   39
    5   25   10   30
   15   35   20   40

C =

    1    2    3    4    5    6    7    8    9   10
   11   12   13   14   15   16   17   18   19   20
   21   22   23   24   25   26   27   28   29   30
   31   32   33   34   35   36   37   38   39   40

Package: image