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
-
Select every other element of a vector
35873 Solvers
-
Read a column of numbers and interpolate missing data
2349 Solvers
-
Project Euler: Problem 6, Natural numbers, squares and sums.
2519 Solvers
-
Given a window, how many subsets of a vector sum positive
869 Solvers
-
Is the paranthesis sequence balanced ?
193 Solvers
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!