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 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 patch and kernel (row and column , counted from 0 as in P5.2),
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 (P5.1), and outputs use the same units. The kernel is not flipped, as in P5.2. We use valid mode, so a 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 . Then every product is times a weight, and
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 (). 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 patch, so each weight is and the nine weights sum to 1:
Take the patch with a vertical boundary,
Six pixels are 10 and three are 90, so the average is : 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 version is
and on the patch above it gives (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 is the point: , so the weights sum to 1 and a flat region keeps its brightness. Without the 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 sampled on a grid and divided by their sum, so they add up to 1. The width sets how far the blur reaches, and a larger needs a larger grid (a common rule of thumb is to extend the grid out to about ). The 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 per axis ( pixels).
Blurring twice is a bigger blur. Applying along a row twice gives , whose variance is , 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 , 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:
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 on the dark side and 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 , subtract a blurred copy to find the detail , and add some multiple of the detail back. If the blur is the average of the four neighbours and the multiple is 4, then , 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 . 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 (columns) and (rows) are
Prewitt has the same layout with the 2s replaced by 1s. Remember what the signs mean: gives the right column minus the left column, so it is positive where the picture gets brighter to the right. 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 above, dark left and bright right:
Each of the three rows contributes its right-minus-left difference of , weighted in all. because each column is constant from top to bottom: nothing changes vertically. Prewitt on the same patch gives . 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 . 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 to on a 0–255 input (the positive weights add to 4 and ), and sharpen from to . 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 , 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.
Things to try:
- 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).
- Choose Sobel x with Signed colours, then with Clip. Pink edges (negative) disappear under Clip. Then choose Sobel y and see the horizontal edges.
- Turn on noise and compare Box blur, Sobel x and Laplacian: the edge detectors are far more disturbed.
- 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 and are two numbers at each pixel, and : 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:
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)
the Sobel sums are and , so the magnitude is and the direction is . Image rows count downward, so means “down and to the right”, toward the bright corner. In the widget, choose Sobel magnitude to see , , 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):
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 , 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, on the last dark pixel and 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 answers most strongly to a patch shaped like itself, and gives exactly 0 to a patch shaped like Sobel (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 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 times , and the Gaussian is times . Sobel is also a column times a row:
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 , then every row of the result with . 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 .
The saving is in the multiplications. A kernel needs per output pixel, and two 1D kernels need :
- : 9 against 6.
- : 49 against 14.
- : 225 against 30.
For 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 per pixel along , Sobel gives (the difference across two pixels is , times the weights ) and Prewitt gives . 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 . The output is a weighted sum of the errors, and for independent errors the output error has standard deviation
The factor, computed from the weights, is:
- Box blur: . The noise falls to a third.
- Gaussian blur: .
- Prewitt : .
- Sobel : .
- Laplacian: .
- Sharpen: .
(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 gives Sobel the response , so the ratio of edge to noise is , 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 is one 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 learned by the first convolutional layer of AlexNet on 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 and a kernel , the output is (a dot product).
Gradient and direction: , , magnitude , direction in image coordinates (y down). Separable means for a column and a row , which holds exactly when , and then , which costs multiplications per pixel instead of when done as two passes. For Sobel, (smoothing) and (difference).
Code
The same operation in PyTorch (static output from a local run with PyTorch 2.9.1). Shapes are for the batch and 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: 9The 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.
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 ; Gaussian ; sharpen ; Sobel ; Laplacian . 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.
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 /, / and /, rank 1 for Sobel and 2 for the Laplacian, noise factors and , and for Gaussian then Sobel an edge of and noise of (edge over noise against for Sobel alone).
Challenge. Add the Prewitt kernel to the first cell. What is its output on row 1? (The step has height 100, so Prewitt gives on both positions.)
Common mistakes
Quiz
Check your understanding
A kernel has weights that sum to 3. What does it output on a flat region where every pixel is 40?
On a flat patch every product is 40 times a weight, so the output is . A flat region passes through unchanged only when the weights sum to 1, and it gives 0 only when they sum to 0. Dividing by the sum is not part of the operation.
Sobel gives at one pixel and at another. What is the difference between the two pixels?
Sobel is the right column minus the left column, so a negative value means the patch is darker on the right, and a positive value means it is brighter on the right. Both are edges of the same strength. The values say nothing about which pixel of the input is darker overall, and one kernel produced both.
White noise with standard deviation 10 goes through the box blur, the Gaussian blur and the Laplacian. Which output has the largest noise?
The output noise is . The Laplacian has weights , so and the output noise is about 45. The blurs reduce the noise (factors 0.33 and 0.375), and the factor differs from kernel to kernel.
Which of these kernels cannot be written as a column times a row?
A column times a row has rank 1. The Laplacian has rank 2: its rows are not all multiples of one another, so it cannot be split. The other three are explicit products of a column and a row.
What does the first convolutional layer of a trained image CNN such as AlexNet tend to contain?
Krizhevsky et al. (2012) describe many orientation- and frequency-selective kernels and colour blobs in the 96 first-layer kernels. Training does not reproduce the textbook kernels exactly, does not force the weights to sum to 0, and does change the first layer like every other one.
Exercises
- 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 answer
It gives 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. - Compute Sobel and Sobel on the patch with rows , , . What do you conclude about a slope of 10 per pixel?
Show answer
and (each column is constant). The ramp rises by 10 per pixel, and Sobel gives : dividing by 8 recovers the slope. - Compute the Laplacian on the patch with rows , , .
Show answer
The four neighbours sum to and four times the centre is , so the output is . It is negative because the centre is brighter than its neighbours. - Compute , , the magnitude and the direction of Sobel on the patch with rows , , .
Show answer
because each row is constant. . The magnitude is 320 and the direction is : brightness increases upward (toward the bright top row). - Noise with standard deviation 10 goes through Sobel and through the box blur. What is the noise standard deviation at each output?
Show answer
for Sobel and for the box blur. - Code: in the first cell, apply Sobel to the step image. What do you expect and why?
Show answer
All zeros. The image does not change from top to bottom, so every column is constant and the bottom-minus-top differences are 0.