# 2D convolution in TikZ: input, kernel and output explained

> How the 2D convolution figure (input, kernel, output) is drawn in TikZ with matrix of nodes, cell styles and anchors, and two computed variations.

URL: https://www.labcanvas.com/tikz/examples/machine-learning/2d-convolution

Updated 2026-11-22. Original figure: 2D convolution, © Petar Veličković, MIT licence (licence text: https://www.labcanvas.com/tikz-library/credits.html#petarv), from https://github.com/PetarV-/TikZ/blob/86aee049f5355d77c598b936399e42caf8941e60/2D%20Convolution/2d_convolution.tex. Walkthrough and variations by LabCanvas; the variation code is CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/). Pictures typeset with TeX Live 2026 and PGF 3.1.12. Category: [TikZ neural network and machine learning examples](https://www.labcanvas.com/tikz/examples/machine-learning).

## Quick answer

This figure shows one step of a 2D convolution: a 3 × 3 window of the 7 × 7 input I (red) is multiplied cell by cell with the kernel K (blue) and summed into one cell of the output I ∗ K (green). All three grids are TikZ matrices of nodes, so every cell has a name such as `mtr-1-4` that the red and green frames, the dotted lines and the small ×1 and ×0 labels use as anchors. The cells are coloured with the `|[fill=red!30]|` prefix, and the matrices are placed side by side with the `positioning` library.

## The figure and its code

![A 2D convolution: a 7 by 7 grid of zeros and ones labelled I with a red-framed 3 by 3 window in the top right whose cells carry small blue ×1 and ×0 marks, a star, a light blue 3 by 3 kernel K with entries 1 0 1, 0 1 0, 1 0 1, an equals sign and a 5 by 5 output grid I ∗ K with the value 4 framed in green; dotted blue and green lines join the window, the kernel and the output cell.](https://www.labcanvas.com/tikz-snippets/fig-2d-convolution/original.webp)

Copyright (c) 2016 Petar Veličković, MIT licence (https://www.labcanvas.com/tikz-library/credits.html#petarv). The code below is exactly the library's file (pdfLaTeX); its first lines name the source and the licence, and the MIT licence asks that they stay with the code. Open it in the TikZ editor from the page: https://www.labcanvas.com/tikz/examples/machine-learning/2d-convolution

```latex
% 2D convolution
% Source: https://github.com/PetarV-/TikZ/blob/86aee049f5355d77c598b936399e42caf8941e60/2D%20Convolution/2d_convolution.tex
% Copyright (c) 2016 Petar Veličković. MIT licence: https://github.com/PetarV-/TikZ/blob/master/LICENSE
% The licence’s copyright and permission notice: https://www.labcanvas.com/tikz-library/credits.html
\documentclass[crop, tikz]{standalone}
\usepackage{tikz}

\usetikzlibrary{matrix,positioning}

\begin{document}
\begin{tikzpicture}

	\matrix (mtr) [matrix of nodes,row sep=-\pgflinewidth, nodes={draw}]
	{
		0 & 1 & 1 & |[fill=red!30]| 1 & |[fill=red!30]| 0 & |[fill=red!30]| 0 & 0\\
		0 & 0 & 1 & |[fill=red!30]| 1 & |[fill=red!30]| 1 & |[fill=red!30]| 0 & 0\\
		0 & 0 & 0 & |[fill=red!30]| 1 & |[fill=red!30]| 1 & |[fill=red!30]| 1 & 0\\
		0 & 0 & 0 & 1 & 1 & 0 & 0\\
		0 & 0 & 1 & 1 & 0 & 0 & 0\\
		0 & 1 & 1 & 0 & 0 & 0 & 0\\
		1 & 1 & 0 & 0 & 0 & 0 & 0\\
	};

	\draw[very thick, red] (mtr-1-4.north west) rectangle (mtr-3-6.south east);

	\node [below= of mtr-5-4.south] (lm) {$\bf I$};

	\node[right = 0.2em of mtr] (str) {$*$};

	\matrix (K) [right=0.2em of str,matrix of nodes,row sep=-\pgflinewidth, nodes={draw, fill=blue!30}]
	{
		1 & 0 & 1 \\
		0 & 1 & 0 \\
		1 & 0 & 1 \\
	};
	\node [below = of K-3-2.south] (lk) {$\bf K$};

	\node [right = 0.2em of K] (eq) {$=$};

	\matrix (ret) [right=0.2em of eq,matrix of nodes,row sep=-\pgflinewidth, nodes={draw}]
	{
		1 & 4 & 3 & |[fill=green!30]| 4 & 1\\
		1 & 2 & 4 & 3 & 3\\
		1 & 2 & 3 & 4 & 1\\
		1 & 3 & 3 & 1 & 1\\
		3 & 3 & 1 & 1 & 0\\
	};
	\node [below = of ret-4-3.south] (lim) {${\bf I} * {\bf K}$};

	\draw[very thick, green] (ret-1-4.north west) rectangle (ret-1-4.south east);

	\draw[densely dotted, blue, thick] (mtr-1-4.north west) -- (K-1-1.north west);
	\draw[densely dotted, blue, thick] (mtr-3-4.south west) -- (K-3-1.south west);
	\draw[densely dotted, blue, thick] (mtr-1-6.north east) -- (K-1-3.north east);
	\draw[densely dotted, blue, thick] (mtr-3-6.south east) -- (K-3-3.south east);

	\draw[densely dotted, green, thick] (ret-1-4.north west) -- (K-1-1.north west);
	\draw[densely dotted, green, thick] (ret-1-4.south west) -- (K-3-1.south west);
	\draw[densely dotted, green, thick] (ret-1-4.north east) -- (K-1-3.north east);
	\draw[densely dotted, green, thick] (ret-1-4.south east) -- (K-3-3.south east);

	\matrix (K) [right=0.2em of str,matrix of nodes,row sep=-\pgflinewidth, nodes={draw, fill=blue!10}]
	{
		1 & 0 & 1 \\
		0 & 1 & 0 \\
		1 & 0 & 1 \\
	};

	\draw[very thick, blue] (K-1-1.north west) rectangle (K-3-3.south east);

	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-1-4.south east) (xx) {\scalebox{.5}{$\times 1$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-1-5.south east) (xx) {\scalebox{.5}{$\times 0$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-1-6.south east) (xx) {\scalebox{.5}{$\times 1$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-2-4.south east) (xx) {\scalebox{.5}{$\times 0$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-2-5.south east) (xx) {\scalebox{.5}{$\times 1$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-2-6.south east) (xx) {\scalebox{.5}{$\times 0$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-3-4.south east) (xx) {\scalebox{.5}{$\times 1$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-3-5.south east) (xx) {\scalebox{.5}{$\times 0$}};
	\node[anchor=south east, inner sep=0.01em, blue] at (mtr-3-6.south east) (xx) {\scalebox{.5}{$\times 1$}};

\end{tikzpicture}
\end{document}
```

## The input as a matrix of nodes

*Lines 5–22 of the code.*

The document class is `standalone` with the `tikz` and `crop` options, so the page is cropped to the picture; the drawing needs the `matrix` library for `matrix of nodes` and `positioning` for the placement that follows. In `\matrix (mtr) [matrix of nodes,row sep=-\pgflinewidth, nodes={draw}]`, every cell’s text becomes a node, `nodes={draw}` gives each of them a border, and the cells are named after the matrix: row 1, column 4 is `mtr-1-4`. Cells are separated by `&` and every row ends with `\\`.

`row sep=-\pgflinewidth` moves the rows together by one line width, so the horizontal borders of neighbouring cells lie on top of each other. There is no matching `column sep`, so between columns two borders sit side by side and the vertical lines come out twice as thick as the horizontal ones; adding `column sep=-\pgflinewidth` would even them out. The nine window cells get their colour from the prefix `|[fill=red!30]|`, which passes options to a single cell.

## The window frame and the I label

*Lines 24–28 of the code.*

Because the cells are nodes, their corners are anchors. `\draw[very thick, red] (mtr-1-4.north west) rectangle (mtr-3-6.south east);` frames the window from the north-west corner of its first cell to the south-east corner of its last. The label I is placed with `below= of mtr-5-4.south`: the of-part is an anchor, a point rather than a node, so the label goes one `node distance` (1 cm by default) below the bottom of cell (5, 4), which happens to clear the two rows under it. The ∗ is a node `right = 0.2em of mtr`, 0.2em from the matrix’s right border.

## The kernel, the result and their labels

*Lines 30–50 of the code.*

The kernel is a second matrix named `K`, placed `right=0.2em of str` (right of the ∗) with `nodes={draw, fill=blue!30}` for every cell, and the output matrix `ret` follows the = sign the same way. Placing a whole matrix with `right=… of` works because a matrix is a node. Each label sits `below = of` a middle cell’s south anchor, and the output’s highlighted cell gets both `|[fill=green!30]|` and a green frame from its own corners.

The highlighted value is the sum of the window times the kernel: the window holds 1 0 0, 1 1 0 and 1 1 1, and multiplying cell by cell with 1 0 1, 0 1 0, 1 0 1 leaves 1 + 1 + 1 + 1 = 4. Strictly, a convolution flips the kernel and what CNNs compute is a cross-correlation, but this kernel is the same after a half turn, so both give the same picture.

## Dotted lines between the corners

*Lines 52–60 of the code.*

Eight `densely dotted` lines connect matching corners: from the window’s corners to the kernel’s, such as `(mtr-1-4.north west) -- (K-1-1.north west)`, and from the output cell’s corners to the kernel’s. Using the same anchor names at both ends is what makes the lines form two clean “projection cones”.

## The kernel drawn a second time

*Lines 62–69 of the code.*

Lines 62 to 67 repeat the kernel matrix with the same name and the same placement, `right=0.2em of str`, but with the lighter `fill=blue!10`. The second copy lands exactly on the first and is drawn after the dotted lines, so it covers the ends of the lines and hides the darker first copy entirely: the kernel you see is the light one. The first copy is still needed, because the K label and the = sign were placed from it. Drawing the dotted lines first, or in a `backgrounds` scope, would make the second matrix unnecessary. Line 69 frames the kernel in blue.

## The small ×1 and ×0 labels

*Lines 71–79 of the code.*

Each window cell gets the kernel value it is multiplied by, in its corner: `\node[anchor=south east, inner sep=0.01em, blue] at (mtr-1-4.south east)` puts a node’s south-east corner on the cell’s south-east corner, and `\scalebox{.5}{$\times 1$}` (from graphicx, which TikZ loads) shrinks the text to half size. All nine nodes are named `xx`, which is harmless because none of them is referred to. A `\foreach` over the nine cells reading from the kernel would replace the nine lines, as in the first variation.

## Techniques used

- [Matrix of nodes](https://www.labcanvas.com/tikz/matrix): three grids whose cells are named nodes, coloured one by one with `|[fill=…]|`.
- [Anchors of named nodes](https://www.labcanvas.com/tikz/nodes): `(mtr-1-4.north west)` and `(mtr-3-6.south east)` place frames, lines and labels.
- [Placing nodes with positioning](https://www.labcanvas.com/tikz/nodes): whole matrices placed `right=0.2em of` each other.
- [Dotted lines](https://www.labcanvas.com/tikz/lines): `densely dotted` connectors between matching corners.
- [Neural network diagrams](https://www.labcanvas.com/tikz/neural-networks): convolution, kernels and feature maps in CNN figures.

## Variations

Our own code, CC0 1.0, each typeset with TeX Live 2026 in a standalone document with the preamble lines shown.

### The output computed from the input and the kernel

Here the numbers are data, not typed cells: the input and the kernel are pgfmath arrays, every output cell is the sum of nine products computed in nested `\foreach` loops, and the window position is two macros, `\def\wr{2}\def\wc{1}`. Change the input, the kernel or the window and the picture stays correct. Square cells 6 mm wide placed 6 mm apart share their borders exactly, so all lines have the same width.

![A 7 by 7 grid of zeros and ones with a red 3 by 3 window starting in the third row and second column, a star, a light blue kernel with 1 0 1, 0 1 0, 1 0 1, an equals sign and a 5 by 5 output grid with the cell in the third row and second column shaded green and framed; labels I, K and I ∗ K below.](https://www.labcanvas.com/tikz-snippets/fig-2d-convolution/computed.webp)

*the same convolution with every output value computed by pgfmath; the window starts at row 2, column 1*

Preamble: `\usepackage{tikz}`

```latex
\begin{tikzpicture}[x=6mm, y=-6mm, font=\small,
    cell/.style={draw, minimum size=6mm, inner sep=0pt}]
  % the input and the kernel as pgfmath arrays; the output is computed from them
  \def\I{{{0,1,1,1,0,0,0},{0,0,1,1,1,0,0},{0,0,0,1,1,1,0},{0,0,0,1,1,0,0},
          {0,0,1,1,0,0,0},{0,1,1,0,0,0,0},{1,1,0,0,0,0,0}}}
  \def\K{{{1,0,1},{0,1,0},{1,0,1}}}
  \def\wr{2}\def\wc{1}  % the window's top-left cell (row, column), counted from 0
  % input, with the window shaded
  \fill[red!20] ({\wc-0.5},{\wr-0.5}) rectangle +(3,3);
  \foreach \i in {0,...,6}
    \foreach \j in {0,...,6} {
      \pgfmathtruncatemacro\v{\I[\i][\j]}
      \node[cell] at (\j,\i) {\v};
    }
  \draw[red, very thick] ({\wc-0.5},{\wr-0.5}) rectangle +(3,3);
  % kernel
  \foreach \a in {0,1,2}
    \foreach \b in {0,1,2} {
      \pgfmathtruncatemacro\v{\K[\a][\b]}
      \node[cell, fill=blue!12] at (8+\b, 2+\a) {\v};
    }
  % output: each cell is the sum of the window times the kernel
  \fill[green!25] ({12+\wc-0.5},{1+\wr-0.5}) rectangle +(1,1);
  \foreach \i in {0,...,4}
    \foreach \j in {0,...,4} {
      \gdef\acc{0}
      \foreach \a in {0,1,2}
        \foreach \b in {0,1,2} {
          \pgfmathtruncatemacro\ii{\i+\a}
          \pgfmathtruncatemacro\jj{\j+\b}
          \pgfmathtruncatemacro\tmp{\acc + \I[\ii][\jj]*\K[\a][\b]}
          \global\let\acc\tmp
        }
      \node[cell] at (12+\j, 1+\i) {\acc};
    }
  \draw[green!50!black, very thick] ({12+\wc-0.5},{1+\wr-0.5}) rectangle +(1,1);
  \node at (3, 7.4) {$\mathbf{I}$};
  \node at (7, 3) {$*$};
  \node at (9, 5.4) {$\mathbf{K}$};
  \node at (11, 3) {$=$};
  \node at (14, 6.4) {$\mathbf{I} * \mathbf{K}$};
\end{tikzpicture}
```

### Padding and stride

The two words that change the output size. A 5 × 5 input gets a ring of zero padding (dashed cells, found with a pgfmath test, `(\i<0) || (\i>4) || …`), and the 3 × 3 kernel moves two cells at a time: the red and blue frames are its first two positions, and they fill the first two cells of the 3 × 3 output. The formula beside it gives the output size for any input size n, padding p, kernel size k and stride s.

![A 5 by 5 grey grid surrounded by a ring of dashed cells containing 0, a red 3 by 3 frame at the top-left corner and a dashed blue frame two cells to the right, overlapping by one column; to the right a 3 by 3 output grid whose first two cells are red and blue, and the formula o = floor of (n + 2p − k) over s, plus 1, giving 3.](https://www.labcanvas.com/tikz-snippets/fig-2d-convolution/stride-padding.webp)

*zero padding p = 1 and stride s = 2: two kernel positions and the 3 × 3 output they fill*

Preamble: `\usepackage{tikz}`

```latex
\begin{tikzpicture}[x=5mm, y=-5mm, font=\footnotesize,
    cell/.style={draw, minimum size=5mm, inner sep=0pt}]
  % a 5 x 5 input padded with one ring of zeros (rows and columns -1 to 5)
  \foreach \i in {-1,...,5}
    \foreach \j in {-1,...,5} {
      \pgfmathtruncatemacro\pad{(\i<0) || (\i>4) || (\j<0) || (\j>4)}
      \ifnum\pad=1
        \node[cell, dashed, gray] at (\j,\i) {0};
      \else
        \node[cell, fill=gray!10] at (\j,\i) {};
      \fi
    }
  % the first two positions of a 3 x 3 kernel moved with stride 2
  \draw[red, very thick] (-1.5,-1.5) rectangle +(3,3);
  \draw[blue, very thick, dashed] (0.5,-1.5) rectangle +(3,3);
  % the 3 x 3 output: one cell per kernel position (the first two shaded)
  \fill[red!30] (8.5,0.5) rectangle +(1,1);
  \fill[blue!30] (9.5,0.5) rectangle +(1,1);
  \foreach \i in {0,1,2}
    \foreach \j in {0,1,2}
      \node[cell] at (9+\j, 1+\i) {};
  \node[align=left, anchor=west] at (7.6, 5) {$o = \left\lfloor \frac{n + 2p - k}{s} \right\rfloor + 1$\\[2pt]
    $n=5,\ p=1,\ k=3,\ s=2$: $o = 3$};
  \node at (2, 6.6) {input with padding $p=1$};
  \node at (10, -0.9) {output};
\end{tikzpicture}
```

## Frequently asked questions

### How do I draw a convolution in TikZ?

Draw the input, the kernel and the output as matrices of nodes (\usetikzlibrary{matrix}), colour the window cells with |[fill=red!30]| and frame them with a rectangle from the first cell’s north west anchor to the last cell’s south east anchor. The computed variation on this page draws the whole figure from two arrays.

### Why are the vertical lines thicker than the horizontal ones in my grid?

Neighbouring cells each draw their own border. row sep=-\pgflinewidth makes the horizontal borders overlap; add column sep=-\pgflinewidth for the vertical ones, or use cells of a fixed size placed exactly one cell width apart.

### Is this a convolution or a cross-correlation?

What CNNs compute, and what the figure shows, is a cross-correlation: the kernel is not flipped. This kernel is symmetric under a half turn, so a true convolution gives the same values.

## References

- [PetarV-/TikZ at commit 86aee04: 2D Convolution/2d_convolution.tex (MIT licence)](https://github.com/PetarV-/TikZ/blob/86aee049f5355d77c598b936399e42caf8941e60/2D%20Convolution/2d_convolution.tex)
- [PGF/TikZ manual, §20 Matrices and Alignment](https://tikz.dev/tikz-matrices)
- [PGF/TikZ manual, §20.3.2 Setting and Adjusting Column and Row Spacing](https://tikz.dev/tikz-matrices#sec-20.3.2)
- [PGF/TikZ manual, §59.1 Matrices of Nodes](https://tikz.dev/library-matrix#sec-59.1)
- [PGF/TikZ manual, §14.4 The Rectangle Operation](https://tikz.dev/tikz-paths#sec-14.4)
- [PGF/TikZ manual, §15.3.2 Graphic Parameters: Dash Pattern (densely dotted)](https://tikz.dev/tikz-actions#sec-15.3.2)
- [PGF/TikZ manual, §17.5.3 Advanced Placement Options (positioning)](https://tikz.dev/tikz-shapes#sec-17.5.3)
- [PGF/TikZ manual, §88 Repeating Things: The Foreach Statement](https://tikz.dev/pgffor)
- [PGF/TikZ manual, §94.2 Operators (||, comparisons)](https://tikz.dev/math-parsing#sec-94.2)
- [PGF/TikZ manual, §94.3.8 Miscellaneous Functions (array)](https://tikz.dev/math-parsing#sec-94.3.8)

## TikZ guides for these techniques

- [TikZ matrix: matrices, arrays of nodes and array diagrams](https://www.labcanvas.com/tikz/matrix): TikZ matrix library: matrix of nodes and math nodes, & and \\, cell names like (m-1-2), styles, brackets, highlighted cells, and array diagrams.
- [TikZ neural network diagrams: perceptron, MLP, CNN, LSTM and transformer](https://www.labcanvas.com/tikz/neural-networks): Neural network diagrams in LaTeX with TikZ: perceptron, MLP from \foreach loops, labelled weights, CNN feature maps, RNN, LSTM, autoencoder, transformer.
- [TikZ nodes: shapes, anchors, positioning and labels](https://www.labcanvas.com/tikz/nodes): How TikZ nodes work: shapes, size (inner sep, minimum size), all anchors, the positioning library (right=of, node distance), labels, pins and scaling.
- [TikZ lines: dashed, dotted, thickness and line width](https://www.labcanvas.com/tikz/lines): TikZ lines: dashed and dotted styles with their exact patterns, ultra thin to ultra thick widths, dash pattern, caps and joins, double lines, grids.
