Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Kernels as feature detectors

P5.340 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A kernel is a small template, and the output says how much each patch of the picture looks like it. Hand-made kernels show what one convolution can do, and a CNN learns its own kernels of the same kind.

  • The first layer of a trained image CNN holds kernels that often look like oriented edge and colour-blob detectors, much like the hand-made ones here. (P5.8: What do CNNs learn?)
  • A CNN does not use fixed kernels: it starts with random ones and learns the nine (or more) numbers by gradient descent. (P5.7: Build a CNN)
  • Splitting a kernel into a column and a row, as done here for the Gaussian and Sobel kernels, is the saving behind factorised convolutions in efficient network designs. (P5.9: The CNN architecture tour)

Before this: The convolution operation, Dot product and cosine similarity

After this lesson you can

  • Say what a kernel's weights add up to decides on a flat region, and use it to tell blur-type kernels (sum 1) from edge-type kernels (sum 0)
  • Compute box blur, Gaussian blur, sharpen, Sobel, Prewitt and Laplacian outputs by hand on a 3 by 3 patch, and read the sign of an edge response
  • Compute gradient magnitude and direction from the two Sobel outputs, and choose how to display values outside 0–255
  • Explain why edge kernels amplify noise and why they are paired with smoothing, and recognise a separable kernel and its saving

Take one picture and make two new ones. In the first, every pixel is blurred a little. In the second, flat regions are all the same grey, and only the outlines of the shapes remain. No neural network and no training is needed for either. Each comes from sliding a 3×33\times3 grid of nine numbers over the picture (P5.2), and the only difference between them is which nine numbers.

This lesson tours the most useful grids: blur, sharpen and the edge detectors. A CNN uses the same operation, but it learns the numbers instead of having them written by hand.

One patch, one score

P5.2 explained the sliding. We need one fact from it: at each position, the output pixel is the sum of the products of the kernel’s weights and the patch under it. For a 3×33\times3 patch P\mathbf{P} and kernel K\mathbf{K} (row aa and column cc, counted from 0 as in P5.2),

O=∑a=02∑c=02Ka,cPa,c,O=\sum_{a=0}^{2}\sum_{c=0}^{2}K_{a,c}P_{a,c},

Read the nine patch values as one vector and the nine weights as another, and this is a dot product (P1.B3): large and positive when the vectors line up, near zero when unrelated, negative when opposed. So the output is a similarity score between the patch and the kernel: a kernel detects the patches that look like itself.

Here, pictures are grey, stored as numbers from 0 (black) to 255 (white) with shape (H,W)(H,W) (P5.1), and outputs use the same units. The kernel is not flipped, as in P5.2. We use valid mode, so a 3×33\times3 kernel makes the output one pixel smaller on every side; P5.4 covers padding.

The one rule: what do the weights add up to?

Put a flat patch under any kernel: every pixel has the same value cc. Then every product is cc times a weight, and

O=c∑a,cKa,c.O=c\sum_{a,c}K_{a,c}.

The output on a flat region is the flat value times the sum of the kernel’s weights. This one line sorts the classic kernels into two families.

  • Sum 1. The flat value passes through unchanged (50→5050\to50). Blur and sharpen kernels are like this, so they keep the overall brightness.
  • Sum 0. A flat patch gives 0, whatever its brightness. Edge detectors are like this: they must say “nothing here” on a flat wall, whether the wall is dark or bright.

Any other sum scales the brightness: a sum of 3 makes flat regions three times brighter.

Blur: averaging the neighbours

The box blur replaces each pixel by the average of its 3×33\times3 patch, so each weight is 19\tfrac19 and the nine weights sum to 1:

Kbox=19(111111111).\mathbf{K}_{\text{box}}=\frac19\begin{pmatrix}1&1&1\\1&1&1\\1&1&1\end{pmatrix}.

Take the patch with a vertical boundary,

P=(101090101090101090).\mathbf{P}=\begin{pmatrix}10&10&90\\10&10&90\\10&10&90\end{pmatrix}.

Six pixels are 10 and three are 90, so the average is (6⋅10+3⋅90)/9=36.7(6\cdot10+3\cdot90)/9=36.7: the output lies between the dark and bright values, which is what blurring a boundary should do. The Gaussian blur keeps the idea but weights the centre more, because nearby pixels should matter more than far ones. The common 3×33\times3 version is

Kgauss=116(121242121),\mathbf{K}_{\text{gauss}}=\frac1{16}\begin{pmatrix}1&2&1\\2&4&2\\1&2&1\end{pmatrix},

and on the patch above it gives (120+240+120)/16=30(120+240+120)/16=30 (one sum per row of the patch). The centre pixel is dark, and it counts for 4 of the 16 shares, so the Gaussian answer is closer to the dark value than the box answer. The 116\tfrac1{16} is the point: 1+2+1+2+4+2+1+2+1=161+2+1+2+4+2+1+2+1=16, so the weights sum to 1 and a flat region keeps its brightness. Without the 116\tfrac1{16} the output would be 16 times too bright.

Blurring removes detail, and noise too: averaging nine numbers with independent errors makes the errors partly cancel (the noise section gives the size).

Go deeper Where the Gaussian weights come from, and bigger blurs

The weights of a Gaussian blur come from the bell curve e−(x2+y2)/(2σ2)e^{-(x^2+y^2)/(2\sigma^2)} sampled on a grid and divided by their sum, so they add up to 1. The width σ\sigma sets how far the blur reaches, and a larger σ\sigma needs a larger grid (a common rule of thumb is to extend the grid out to about 3σ3\sigma). The 1,2,11,2,1 pattern is the third row of Pascal’s triangle divided by 4. It is a standard small approximation to a Gaussian, with a variance of 0.50.5 per axis (σ≈0.71\sigma\approx0.71 pixels).

Blurring twice is a bigger blur. Applying 14(1,2,1)\tfrac14(1,2,1) along a row twice gives 116(1,4,6,4,1)\tfrac1{16}(1,4,6,4,1), whose variance is 1.01.0, the sum of the two variances. This is a property of Gaussians: widths combine by adding variances.

Sharpen: the pixel plus its difference from its neighbours

A common sharpening kernel is the first line below. Its weights sum to 5−4=15-4=1, so flat regions are unchanged. To see what it does, write it as the identity kernel (a 1 in the middle, zeros elsewhere, which copies the pixel) minus an edge term:

Ksharp=(0−10−15−10−10)=(000010000)−(0101−41010).\begin{aligned} \mathbf{K}_{\text{sharp}}&=\begin{pmatrix}0&-1&0\\-1&5&-1\\0&-1&0\end{pmatrix}\\ &=\begin{pmatrix}0&0&0\\0&1&0\\0&0&0\end{pmatrix}\\ &\quad-\begin{pmatrix}0&1&0\\1&-4&1\\0&1&0\end{pmatrix}. \end{aligned}

The edge term is the Laplacian (below). It is large when a pixel differs from its four neighbours, and subtracting it pushes a bright pixel brighter and a dark pixel darker than their surroundings. On a flat patch it is 0. Sharpening adds contrast at existing edges. It does not bring back detail that a blur or low resolution has destroyed, since the kernel only combines the pixels that are there.

Two side effects matter. Sharpening overshoots: next to a step from 0 to 100 it produces −100-100 on the dark side and 200200 on the bright side, outside the original range (see the code below), and displays it clipped. And it amplifies noise (see the noise section).

Go deeper Sharpening as unsharp masking

Photographers call this idea unsharp masking: take the original xx, subtract a blurred copy to find the detail x−blur(x)x-\mathrm{blur}(x), and add some multiple of the detail back. If the blur is the average of the four neighbours and the multiple is 4, then x+4(x−14∑neighbours)=5x−∑neighboursx+4\bigl(x-\tfrac14\sum\text{neighbours}\bigr)=5x-\sum\text{neighbours}, exactly the kernel above. Using a Gaussian blur and a smaller multiple gives a gentler, more flexible sharpen.

Edge kernels: differences, not averages

An edge is a place where brightness changes quickly. The simplest way to measure change is a difference: the right neighbour minus the left neighbour. As a kernel row that is (−1, 0, 1)(-1,\,0,\,1). Its weights sum to 0, so a flat patch gives exactly 0, and a patch that rises from left to right gives a positive number.

A single row is easily disturbed by one odd pixel, so the standard kernels apply the same difference to three rows and add them. Prewitt counts the three rows equally. Sobel counts the middle row twice, which gives the nearest row more say. They are named after Judith Prewitt and Irwin Sobel. In the cross-correlation convention used here, the kernels for changes along xx (columns) and yy (rows) are

KxSobel=(−101−202−101)\mathbf{K}^{\text{Sobel}}_x=\begin{pmatrix}-1&0&1\\-2&0&2\\-1&0&1\end{pmatrix} KySobel=(−1−2−1000121)\mathbf{K}^{\text{Sobel}}_y=\begin{pmatrix}-1&-2&-1\\0&0&0\\1&2&1\end{pmatrix}

Prewitt has the same layout with the 2s replaced by 1s. Remember what the signs mean: KxK_x gives the right column minus the left column, so it is positive where the picture gets brighter to the right. KyK_y gives the bottom row minus the top row, and rows count downward in an image, so it is positive where the picture gets brighter going down. (A textbook that flips the kernel, true convolution as in P5.2, gets the opposite signs. Libraries like PyTorch do not flip.)

On the patch P\mathbf{P} above, dark left and bright right:

Gx=∑Ka,cPa,c=4⋅(90−10)=320,Gy=0.\begin{aligned} G_x&=\sum K_{a,c}P_{a,c}\\ &=4\cdot(90-10)=320,\\ G_y&=0. \end{aligned}

Each of the three rows contributes its right-minus-left difference of 8080, weighted 1+2+1=41+2+1=4 in all. Gy=0G_y=0 because each column is constant from top to bottom: nothing changes vertically. Prewitt xx on the same patch gives 3⋅80=2403\cdot80=240. On a flat patch of 50s every kernel above gives exactly 0.

A boundary that goes from bright on the left to dark on the right gives −320-320. The sign is not “less of an edge”. It is an edge of the opposite kind, and a display rule that throws it away throws away half the edges.

Showing results that are not pictures

A picture’s pixels live in 0–255. Filtered values do not. The Sobel kernels can output anything from −1020-1020 to 10201020 on a 0–255 input (the positive weights add to 4 and 4⋅255=10204\cdot255=1020), and sharpen from −1020-1020 to 12751275. Before a result can be shown on a screen, it needs a rule to map it to a pixel brightness. There are four common ones:

  • Clip: values below 0 become 0 and values above 255 become 255. Fine for blur, wrong for edge kernels: every negative response turns black.
  • Rescale: the smallest value becomes black and the largest white. Nothing is lost, but zero is no longer a fixed grey.
  • Absolute value: show ∣O∣|O|, scaled so that the largest is white. It shows the size of a change but not its direction.
  • Signed colours: a diverging scale with zero in the middle. The widget uses blue for positive, pink for negative and light grey for zero, with a numbered legend. This is the only rule that keeps both size and sign.

Auto picks signed colours when the weights sum to 0, clip when they do not, and absolute value for the Sobel magnitude.

See it: apply the kernels

Pick a kernel and a display rule, then tap or drag on either picture (or focus one and use the arrow keys) to choose an output pixel. The blue square on the input is the patch that makes it, and the three small grids show the patch, the kernel and their products, whose sum is the output pixel.

Picture
Noise

Built-in scene made by code: a left-to-right brightness ramp, a disc, a dark rectangle, a diagonal line and two letter-like strokes. Noise is random and fixed (the same dots every time), in 0–255 units.

Kernel
Sum of weights0

Right column minus left column, middle row counted twice. Positive where brightness rises to the right. The weights sum to 0.

Show output as

Auto: signed colours if the weights sum to 0, absolute value for the magnitude, otherwise clip.

Input (80×80, values 0–255)
Output (78×78, signed colours)
−684 (negative)0+684 (positive)

Output values run from −572 to 684. Input values are in 0–255.

One output pixel (row 35, column 33 of the output)
Patch (input)
×
Kernel
=
Products

Sum of products = −433.

The output border is blank: valid mode drops one pixel on each side (P5.4 covers padding).

Apply a 3 by 3 kernel to a built-in test scene or to your own photo. Left: the input, 80 by 80 grey pixels. Right: the output in valid mode, 78 by 78, with the chosen display rule and a legend. Below: the patch under the blue square, the kernel and their products. A photo is shrunk to 80 by 80 grey pixels inside your browser and is never uploaded or stored.

Things to try:

  1. Choose Box blur, then Gaussian blur. Compare the edge of the disc. Both keep the ramp and the overall brightness (the weights sum to 1).
  2. Choose Sobel x with Signed colours, then with Clip. Pink edges (negative) disappear under Clip. Then choose Sobel y and see the horizontal edges.
  3. Turn on noise and compare Box blur, Sobel x and Laplacian: the edge detectors are far more disturbed.
  4. Choose Sharpen: edges get a bright rim on the bright side and a dark rim on the dark side (the overshoot).

Gradient magnitude and direction

Sobel xx and yy are two numbers at each pixel, GxG_x and GyG_y: how fast brightness changes along each axis. Together they form the image gradient, an arrow that points toward the brightest neighbours. (This is the gradient of the picture with respect to position. It is not the gradient of a loss with respect to weights that we colour orange in the training lessons.) Two numbers describe the arrow:

magnitude=Gx2+Gy2,direction=atan2⁡(Gy, Gx).\begin{aligned} \text{magnitude}&=\sqrt{G_x^2+G_y^2},\\ \text{direction}&=\operatorname{atan2}(G_y,\,G_x). \end{aligned}

The magnitude says how strong the edge is, whichever way it faces, so it is the usual edge map. The direction says which way brightness rises, and the edge itself runs perpendicular to the gradient.

For a corner patch (dark top left, bright bottom right)

P=(101010101090109090)\mathbf{P}=\begin{pmatrix}10&10&10\\10&10&90\\10&90&90\end{pmatrix}

the Sobel sums are Gx=240G_x=240 and Gy=240G_y=240, so the magnitude is 2402≈339.4240\sqrt2\approx339.4 and the direction is 45∘45^\circ. Image rows count downward, so +45∘+45^\circ means “down and to the right”, toward the bright corner. In the widget, choose Sobel magnitude to see GxG_x, GyG_y, the magnitude and the angle at the selected pixel, and an arrow toward the brighter side.

The Laplacian: second differences

Sobel looks at how brightness changes. The Laplacian looks at how that change changes (a second difference):

KLap=(0101−41010).\mathbf{K}_{\text{Lap}}=\begin{pmatrix}0&1&0\\1&-4&1\\0&1&0\end{pmatrix}.

It is the sum of the four neighbours minus four times the centre: positive when the centre is darker than its neighbours on average, negative when it is brighter. Its weights sum to 1+1+1+1−4=01+1+1+1-4=0, so flat regions give 0. It also gives 0 on a perfectly straight ramp (a constant slope), where Sobel gives a constant. At a step from 0 up to 100 it makes a pair, +100+100 on the last dark pixel and −100-100 on the first bright one, and the edge sits at the sign change (a “zero-crossing”). It has no direction: one kernel finds edges of any orientation, but the sign pair and the strong noise response (below) make it harder to read than a Sobel magnitude.

What a kernel “detects”

Among patches with the same overall size (the same vector norm), the dot product is largest when the patch points the same way as the kernel (P1.B3, Cauchy–Schwarz). Sobel xx answers most strongly to a patch shaped like itself, and gives exactly 0 to a patch shaped like Sobel yy (the two kernels are perpendicular as vectors). A kernel is still not a shape recogniser. Two limits matter:

  • A kernel with positive weights responds to brightness itself. A box blur “detects” any bright patch. Only when the weights sum to 0 does a bright but featureless patch give 0. A fair similarity divides by the sizes of the patch and kernel (the cosine similarity of P1.B3), and a plain convolution does not.
  • Edge kernels detect a change in one direction. Sobel xx answers to a vertical boundary of any contrast, and also to noise that happens to look like one.

A CNN relies on this reading: each kernel in a layer looks for one pattern, and its output map says where it is. P5.5 extends it to colour and to many kernels at once.

Separable kernels: a column times a row

The box kernel is 13(1,1,1)⊤\tfrac13(1,1,1)^\top times 13(1,1,1)\tfrac13(1,1,1), and the Gaussian is 14(1,2,1)⊤\tfrac14(1,2,1)^\top times 14(1,2,1)\tfrac14(1,2,1). Sobel xx is also a column times a row:

(−101−202−101)=(121)(−101).\begin{pmatrix}-1&0&1\\-2&0&2\\-1&0&1\end{pmatrix}=\begin{pmatrix}1\\2\\1\end{pmatrix}\begin{pmatrix}-1&0&1\end{pmatrix}.

A kernel that is a column times a row is called separable. The filtering can then be done as two one-dimensional passes: filter every column with (1,2,1)⊤(1,2,1)^\top, then every row of the result with (−1,0,1)(-1,0,1). The answer is the same (the code below checks it). It also explains Sobel: smooth down the rows, then take a difference across the columns. The smoothing makes it steadier than the one-row difference. Prewitt is the same with the smoothing (1,1,1)⊤(1,1,1)^\top.

The saving is in the multiplications. A k×kk\times k kernel needs k2k^2 per output pixel, and two 1D kernels need 2k2k:

  • k=3k=3: 9 against 6.
  • k=7k=7: 49 against 14.
  • k=15k=15: 225 against 30.

For 3×33\times3 the gain is small, and for large blurs it is large. Not every kernel splits. A kernel is separable exactly when, as a matrix, it has rank 1. The Laplacian and the sharpen kernel have rank 2, so they are not (the code checks). Some efficient networks replace a large kernel by a column followed by a row (P5.9).

Go deeper Sobel and Prewitt are scaled derivatives

On a pure ramp, where brightness rises by mm per pixel along xx, Sobel xx gives 8m8m (the difference across two pixels is 2m2m, times the weights 1+2+1=41+2+1=4) and Prewitt xx gives 6m6m. So dividing by 8 (Sobel) or 6 (Prewitt) turns the output into the slope in brightness per pixel. The code check below uses a ramp of slope 3 and recovers exactly 3.0 for both. Without the division the numbers are larger, but they only change by a constant, which does not matter when you only compare edge strengths.

Noise, and why edge detectors come with smoothing

Real pictures have noise: small random errors in each pixel. Suppose every pixel has an independent error with standard deviation σ\sigma. The output is a weighted sum of the errors, and for independent errors the output error has standard deviation

σout=σ∑a,cKa,c2.\sigma_{\text{out}}=\sigma\sqrt{\sum_{a,c}K_{a,c}^2}.

The factor, computed from the weights, is:

  • Box blur: 9/81=0.33\sqrt{9/81}=0.33. The noise falls to a third.
  • Gaussian blur: 36/256=0.375\sqrt{36/256}=0.375.
  • Prewitt xx: 6≈2.45\sqrt6\approx2.45.
  • Sobel xx: 12≈3.46\sqrt{12}\approx3.46.
  • Laplacian: 20≈4.47\sqrt{20}\approx4.47.
  • Sharpen: 29≈5.39\sqrt{29}\approx5.39.

(Simulating on random noise agrees to within a percent.) The blurs average the noise out, and the edge and sharpen kernels amplify it several times over. The signal does not grow like that: a step of height hh gives Sobel xx the response 4h4h, so the ratio of edge to noise is 4h/(3.46σ)≈1.15 h/σ4h/(3.46\sigma)\approx1.15\,h/\sigma, and when the noise is large the edge hides in it.

The standard answer is to smooth first, then detect. Filtering with the Gaussian and then Sobel xx is one 5×55\times5 kernel, and in a test with a step of height 1 and pure noise of standard deviation 1 it gives an edge response of 3.0 and a noise level of 1.66. The ratio of edge to noise is about 1.81 against 1.15 for Sobel alone (the code below prints both). The price is the usual one with blur: the edge is spread over four pixels instead of two. Classic edge detectors use the same trade: the Marr–Hildreth detector works with the Laplacian of a Gaussian-smoothed picture, and Canny’s detector smooths with a Gaussian before taking gradients.

From hand-made to learned kernels

All the kernels above were designed by a person. A CNN does not normally use designed kernels: its kernels start as random numbers and are changed by gradient descent (P5.7), as the weights of an MLP are (P4.8). Yet the result is often familiar. Krizhevsky, Sutskever and Hinton (2012) showed the 96 kernels of size 11×11×311\times11\times3 learned by the first convolutional layer of AlexNet on 224×224×3224\times224\times3 input images, and describe “a variety of frequency- and orientation-selective kernels, as well as various colored blobs”. Some respond to edges and stripes of one orientation and spacing, much like Sobel, and some to patches of one colour. Zeiler and Fergus (2014) visualised more of what a trained network responds to. P5.8 shows real learned kernels.

Three cautions. This is what is often seen in the first layer of networks trained on natural images, not a law. Deeper layers are not simple edge detectors: they combine earlier outputs into larger patterns (P5.6, P5.8). And learned kernels are not constrained to sum to 0 or 1, or to be separable, so they are rougher than the textbook ones. A CNN starts with random kernels and learns them; it is not built from Sobel and Gaussian kernels.

Depth: three ways to see it

Intuition

A kernel is a stencil held over a picture, and the output is how well the picture under the stencil matches it. A blur stencil is a smooth bump, so it matches any smooth bright patch. A Sobel stencil has a dark column on one side and a bright column on the other, so it matches a dark-to-bright boundary on that axis.

The picture breaks where a stencil either fits or does not: a kernel gives a number, and matching the opposite pattern gives a negative number, not a blank.

Math

For a patch P\mathbf{P} and a kernel K\mathbf{K}, the output is O=∑a,cKa,cPa,cO=\sum_{a,c}K_{a,c}P_{a,c} (a dot product).

Gradient and direction: Gx=Kx⋅PG_x=\mathbf{K}_x\cdot\mathbf{P}, Gy=Ky⋅PG_y=\mathbf{K}_y\cdot\mathbf{P}, magnitude Gx2+Gy2\sqrt{G_x^2+G_y^2}, direction atan2⁡(Gy,Gx)\operatorname{atan2}(G_y,G_x) in image coordinates (y down). Separable means K=uv⊤\mathbf{K}=\mathbf{u}\mathbf{v}^\top for a column u\mathbf{u} and a row v⊤\mathbf{v}^\top, which holds exactly when rank(K)=1\mathrm{rank}(\mathbf{K})=1, and then O=u⊤PvO=\mathbf{u}^\top\mathbf{P}\mathbf{v}, which costs 2k2k multiplications per pixel instead of k2k^2 when done as two passes. For Sobel, u=(1,2,1)⊤\mathbf{u}=(1,2,1)^\top (smoothing) and v=(−1,0,1)⊤\mathbf{v}=(-1,0,1)^\top (difference).

Code

The same operation in PyTorch (static output from a local run with PyTorch 2.9.1). Shapes are (N,C,H,W)(N,C,H,W) for the batch and (out,in,kH,kW)(\text{out},\text{in},k_H,k_W) for the kernel. A learned layer is the same call with weights that training changes.

import torch
import torch.nn as nn
import torch.nn.functional as F

sobel_x = torch.tensor([[-1., 0., 1.],
                        [-2., 0., 2.],
                        [-1., 0., 1.]])
w = sobel_x.reshape(1, 1, 3, 3)   # (out, in, kH, kW)
x = torch.zeros(1, 1, 6, 8)       # (N, C, H, W)
x[..., 4:] = 100.0                # dark left

y = F.conv2d(x, w)
print("shape:", tuple(y.shape))
print("row 1:", y[0, 0, 1].tolist())

conv = nn.Conv2d(1, 1, 3, bias=False)
with torch.no_grad():
    conv.weight.copy_(w)          # a layer holding Sobel x
print("same:", torch.equal(conv(x), y))
print("weights:", conv.weight.numel())
shape: (1, 1, 4, 6)
row 1: [0.0, 0.0, 400.0, 400.0, 0.0, 0.0]
same: True
weights: 9

The output is positive where brightness rises to the right, so PyTorch does not flip the kernel (P5.2). Training a layer like this one means changing its 9 numbers, starting from random values, until the loss falls.

Try it in Python

The first cell applies five kernels to a step image (6 rows by 8 columns, 0 on the left and 100 on the right), printing each kernel’s weight sum and row 1 of the output, then tries a flat patch.

Five kernels on a step edge

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell gives, for row 1: box 0,0,33,67,100,1000,0,33,67,100,100; Gaussian 0,0,25,75,100,1000,0,25,75,100,100; sharpen 0,0,−100,200,100,1000,0,-100,200,100,100; Sobel xx 0,0,400,400,0,00,0,400,400,0,0; Laplacian 0,0,100,−100,0,00,0,100,-100,0,0. On the flat patch the sum-1 kernels give 50 and the sum-0 kernels give 0.

The second cell checks the column-times-row split, the saving, the rank and the noise numbers.

Separable kernels and noise

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints True twice, the counts 99/66, 4949/1414 and 225225/3030, rank 1 for Sobel and 2 for the Laplacian, noise factors 0.330.33 and 3.473.47, and for Gaussian then Sobel xx an edge of 3.03.0 and noise of 1.661.66 (edge over noise 1.811.81 against 1.151.15 for Sobel alone).

Challenge. Add the Prewitt xx kernel to the first cell. What is its output on row 1? (The step has height 100, so Prewitt gives 3⋅100=3003\cdot100=300 on both positions.)

Common mistakes

Quiz

Check your understanding

  1. A 3×33\times3 kernel has weights that sum to 3. What does it output on a flat region where every pixel is 40?

  2. Sobel xx gives −300-300 at one pixel and +300+300 at another. What is the difference between the two pixels?

  3. White noise with standard deviation 10 goes through the box blur, the Gaussian blur and the Laplacian. Which output has the largest noise?

  4. Which of these kernels cannot be written as a column times a row?

  5. What does the first convolutional layer of a trained image CNN such as AlexNet tend to contain?

Exercises

  1. A kernel has a single non-zero weight, 2, in the centre. What does it do to a flat patch of 50s, and what does it do to a picture?
    Show answerIt gives 50×2=10050\times2=100 on a flat patch: the weights sum to 2, so it doubles every brightness. On a picture it makes everything twice as bright (before clipping), without blurring or finding edges.
  2. Compute Sobel xx and Sobel yy on the patch with rows (10,20,30)(10,20,30), (10,20,30)(10,20,30), (10,20,30)(10,20,30). What do you conclude about a slope of 10 per pixel?
    Show answerGx=4⋅(30−10)=80G_x=4\cdot(30-10)=80 and Gy=0G_y=0 (each column is constant). The ramp rises by 10 per pixel, and Sobel xx gives 8×10=808\times10=80: dividing by 8 recovers the slope.
  3. Compute the Laplacian on the patch with rows (5,5,5)(5,5,5), (5,9,5)(5,9,5), (5,5,5)(5,5,5).
    Show answerThe four neighbours sum to 2020 and four times the centre is 3636, so the output is 20−36=−1620-36=-16. It is negative because the centre is brighter than its neighbours.
  4. Compute GxG_x, GyG_y, the magnitude and the direction of Sobel on the patch with rows (90,90,90)(90,90,90), (10,10,10)(10,10,10), (10,10,10)(10,10,10).
    Show answerGx=0G_x=0 because each row is constant. Gy=(1+2+1)⋅10−(1+2+1)⋅90=−320G_y=(1+2+1)\cdot10-(1+2+1)\cdot90=-320. The magnitude is 320 and the direction is atan2⁡(−320,0)=−90∘\operatorname{atan2}(-320,0)=-90^\circ: brightness increases upward (toward the bright top row).
  5. Noise with standard deviation 10 goes through Sobel xx and through the 3×33\times3 box blur. What is the noise standard deviation at each output?
    Show answer1012≈34.610\sqrt{12}\approx34.6 for Sobel xx and 10/3≈3.310/3\approx3.3 for the box blur.
  6. Code: in the first cell, apply Sobel yy to the step image. What do you expect and why?
    Show answerAll zeros. The image does not change from top to bottom, so every column is constant and the bottom-minus-top differences are 0.

Key takeaways

  • At each position a kernel computes a dot product between its nine weights and the patch under it (P5.2). A large result means the patch looks like the kernel; a small one means it does not. Designing a kernel means choosing what to look for.
  • On a flat patch of value cc the output is cc times the sum of the weights. Blur and sharpen kernels sum to 1, so flat regions keep their brightness. Edge kernels (Prewitt, Sobel, Laplacian) sum to 0, so flat regions give 0 and only changes show up.
  • Box blur averages the patch with equal weights. A Gaussian blur weights the centre more. Sharpen is the identity plus an edge term, so it adds the pixel's difference from its neighbours back to the pixel.
  • Sobel x and y measure how fast brightness changes along each axis, and are signed: positive means brighter toward the right (x) or down (y). The magnitude Gx2+Gy2\sqrt{G_x^2+G_y^2} says how strong the change is, and atan2⁡(Gy,Gx)\operatorname{atan2}(G_y,G_x) says in which direction it points, toward the brighter side.
  • Filtered values can be negative or above 255, so choose a display rule: clip, rescale, absolute value, or signed colours. Edge kernels need the sign or the absolute value. For independent pixel noise, the output noise is multiplied by ∑Ka,c2\sqrt{\sum K_{a,c}^2}: 3.5 for Sobel x, 4.5 for the Laplacian, 0.33 for the box blur. So edge detection is paired with smoothing.
  • A kernel is separable when it is a column times a row, which turns k2k^2 multiplications per pixel into 2k2k. The box, Gaussian, Prewitt and Sobel kernels are separable; the Laplacian is not. Trained CNNs learn their kernels, and the first-layer kernels of AlexNet include many orientation-selective and colour-blob kernels.
Found a mistake? Tell us