MATLAB: Creating Convolution Matrix of 2D Kernel for Different Shapes of Convolution

convolutionimage processingMATLABmatrix formvectorization

MATLAB, for thos who have access to Image Processing Toolbox offers the function convmtx2().
Yet there are 2 issues:
  • It is only available to those who purchased Image PRocessing Toolbox.
  • It creates the matrix for full convolution shape only.
I implemented the matrix form for imfiter() in Generate the Matrix Form of 2D Convolution Kernel. It was written in simple form (No vectorization tricks) for clarity and simplicity for thos who want to learn.
What I'm after is doing somthing similar for Convolution Matrices for the different shapes: full, same, valid.
Namely a function with the following form:
function [ mK ] = CreateImageConvMtx( mH, numRows, numCols, convShape )
%UNTITLED6 Summary of this function goes here
% Detailed explanation goes here
CONVOLUTION_SHAPE_FULL = 1;
CONVOLUTION_SHAPE_SAME = 2;
CONVOLUTION_SHAPE_VALID = 3;
switch(convShape)
case(CONVOLUTION_SHAPE_FULL)
% Code for the 'full' case
case(CONVOLUTION_SHAPE_SAME)
% Code for the 'same' case
case(CONVOLUTION_SHAPE_VALID)
% Code for the 'valid' case
end
end
I would be happy of someone could assist with that.
Again, prefer clarity over performance.
Thank You.

Best Answer

Readability and clarity over performance.
OK, can't get much simpler and more readable then the following:
function [ mK ] = CreateImageConvMtx( mH, nRows, nCols, convShape )
%convShape is 'full', 'same', or 'valid'
impulse=zeros(nRows,nCols);
for i=numel(impulse):-1:1
impulse(i)=1; %Create impulse image corresponding to i-th output matrix column
tmp=sparse( conv2(impulse,mH,convShape) ); %impulse response
Column{i}=tmp(:);
impulse(i)=0;
end
mK=cell2mat(Column);
end