Cyrine Abdelkafi
Cyrine Abdelkafi

Reputation: 159

Implement MATLAB's col2im 'sliding' in Python

col2im and im2col functions in matlab are important for image processing, however by googling there is no efficient implementation for python.

Especially I want to rewrite col2im for python using numpy

I have a matrix and I want to rearrange its columns into block.

The implemntations I found are not reliable by testing them it does not give the same result as matlab.

For im2col, the following implementation works fine

def im2col_sliding(A, size):  
    dy, dx = size  
    xsz = A.shape[1] - dx + 1
    ysz = A.shape[0] - dy + 1
    R = np.empty((xsz * ysz, dx * dy))

    for i in xrange(ysz):  
        for j in xrange(xsz):  
            R[i * xsz + j, :] = A[i:i + dy, j:j + dx].ravel()
    return R  

But the related col2im is bogus !

Assume I a have matrix V of isze size(V) = 1 69169 By running in matlab:

X = col2im(V, [3 3], [265 265], 'sliding'); 

It gives me size(X) is 263 263

But, In the python implementation related to the code I posted for im2col, returns an ndarray of size (263 2) and not (263 263) and the values are incorrect !

any help

Upvotes: 3

Views: 2053

Answers (1)

Divakar
Divakar

Reputation: 221614

For im2col 'sliding'version, we already have few efficient implementations as posted here.

For col2im 'sliding'version, it would just be a reshape away -

def col2im_sliding(B, block_size, image_size):
    m,n = block_size
    mm,nn = image_size
    return B.reshape(nn-n+1,mm-m+1).T 
      # Or simply B.reshape(nn-n+1,-1).T
      # Or B.reshape(mm-m+1,nn-n+1,order='F')

Test runs

MATLAB run -

>> arr = 1:15;
>> arr
arr =
     1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
>> col2im(arr, [3,3], [7,5],'sliding')
ans =                
     1     6    11  %// (7-3+1, 5-3+1) shaped array
     2     7    12
     3     8    13
     4     9    14
     5    10    15

NumPy/Python run -

In [116]: arr
Out[116]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

In [117]: col2im_sliding(arr, [3,3], [7,5])
Out[117]: 
array([[ 1,  6, 11],  # (7-3+1, 5-3+1) shaped array
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14],
       [ 5, 10, 15]])

Upvotes: 4

Related Questions