Mathematica - Convolution

Posted on April 4, 2021
Tags: mathematica
randphoto = ResourceFunction["RandomPhoto"][200];

Convolution is elementwise multiplication. It is NOT the dotproduct matrix multiplication.
X convolve with kernel means
submatrix(X) elementwise multiply by kernel matrix. Example of the

\[kernel = \begin{bmatrix} 2 & 5 \\ -7 & -6 \end{bmatrix}\]

\[\begin{bmatrix} a & b & c\\ d & e & f\\ g & h & i\\ j & k & l \end{bmatrix} \star^{Conv1} \begin{bmatrix} 2 & 5 \\ -7 & -6 \end{bmatrix} = \begin{bmatrix} Sum(\begin{bmatrix} 2a & 5b \\ -7d & -6e \end{bmatrix}) & Conv2\\ Conv3 & Conv4 \\ Conv5 & Conv6\\ \end{bmatrix}\] \[Conv1 = Sum(\begin{bmatrix} 2a & 5b \\ -7d & -6e \end{bmatrix}) = 2a + 5b -7d -6e\]

rphoto2 = Binarize@randphoto;
hlinekernel = {{-1,-1,-1},{2,2,2},{-1,-1,-1}};
vlinekernel = {{-1,2,-1},{-1,2,-1},{-1,2,-1}};
a = ImageConvolve[rphoto2,vlinekernel]
Output
b= ImageConvolve[rphoto2,hlinekernel]
Output
ImageAdd[a,b]
Output
rphoto2
Output
Export["tiger.png",randphoto]
tiger.png