Problem 44832. Generate Convolution Matrix of 2D Kernel with Different Convolution Shapes (Full, Same, Valid)
In this problem the challenge is to build the Matrix Form equivalent of the function `conv2()` of MATLAB.
The function to be built will generate a sparse matrix `mK` which is the convolution matrix of the 2D Kernel 'mH' (Which is an input to the function). The input to the function is the 2D Kernel and dimensions of the image to apply the convolution upon and the shape of the convolution ('full', 'same', 'valid' as in 'conv2()').
The output sparse matrix should match the output of using 'conv2()' on the same image using the same convolution shape.
For instance:
CONVOLUTION_SHAPE_FULL = 1; CONVOLUTION_SHAPE_SAME = 2; CONVOLUTION_SHAPE_VALID = 3;
numRowsImage = 100; numColsImage = 80;
numRowsKernel = 7; numColsKernel = 5;
mI = rand(numRowsImage, numColsImage); mH = rand(numRowsKernel, numColsKernel);
maxThr = 1e-9;
%% Full Convolution
convShape = CONVOLUTION_SHAPE_FULL;
numRowsOut = numRowsImage + numRowsKernel - 1; numColsOut = numColsImage + numColsKernel - 1;
mORef = conv2(mI, mH, 'full'); mK = CreateImageConvMtx(mH, numRowsImage, numColsImage, convShape); mO = reshape(mK * mI(:), numRowsOut, numColsOut);
mE = mO - mORef; assert(max(abs(mE(:))) < maxThr);
The test case will examine all 3 modes. Try to solve it once with very clear code (No vectorization tricks) and then optimize.
A good way to build the output sparse function is using:
mK = sparse(vRows, vCols, vVals, numElementsOutputImage, numElementsInputImage);
Look for the documentation of `sparse()` function for more details.
Solution Stats
Solution Comments
Show commentsProblem Recent Solvers3
Suggested Problems
-
Find the peak 3n+1 sequence value
2501 Solvers
-
Vectorize the digits of an Integer
322 Solvers
-
Find the elements of a matrix according to a defined property.
84 Solvers
-
Construct an index vector from two input vectors in vectorized fashion
391 Solvers
-
Generate a string like abbcccddddeeeee
263 Solvers
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!