Skip to main content

Convolution and gradients

The filters are ready-made. A convolution is the general tool behind many of them: a small table of numbers, the kernel, is laid over every pixel, each number is multiplied by the pixel under it, and the sum is the new value. Choose the numbers and you choose the filter.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
img = stb.Image.open("astronaut.png").thumbnail(256, 256)

# A kernel is a list of rows with an odd number of values each, laid over every pixel as it is.
sharpen = stb.convolve(img, [[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
edges = stb.convolve(img.convert(stb.PixelFormat.GRAY), [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
box = stb.convolve(img, [[1 / 25] * 5] * 5)
sharpen.write("out/sharpen.png")
edges.write("out/edges.png")
box.write("out/box.png")
print(f"sharpen: mean absolute change {stb.mae(img, sharpen):.2f}")
print(f"box 5 x 5: mean absolute change {stb.mae(img, box):.2f}")

# A kernel that is a product of a row and a column can be given as the two, which costs 5 + 5 multiplications per value, not 25.
taps = [[1 / 16, 4 / 16, 6 / 16, 4 / 16, 1 / 16]] # the binomial row, close to a Gaussian with sigma 1
separable = stb.convolve(img, taps, taps)
separable.write("out/binomial.png")
print(f"binomial against gaussian_blur(sigma 1): mean absolute difference {stb.mae(separable, stb.gaussian_blur(img, 1.0)):.2f}")

# An even-sized kernel has no center: an error, not a guess.
try:
stb.convolve(img, [[1, 1], [1, 1]])
except ValueError:
print("a 2 x 2 kernel: rejected")
Output
sharpen: mean absolute change 12.84
box 5 x 5: mean absolute change 8.96
binomial against gaussian_blur(sigma 1): mean absolute difference 0.20
a 2 x 2 kernel: rejected
sharpen kernel
sharpen kernel
edge kernel (gray)
edge kernel (gray)
box 5 x 5
box 5 x 5
binomial, separable
binomial, separable

Kernels​

A kernel has an odd width and an odd height, so it has a center to put on the pixel, and one channel. The same kernel is used on every channel of the picture, alpha included. A few of the usual ones:

  • sharpen: [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]. The numbers add up to 1, so flat areas stay as they are and edges are stressed.
  • edges: [[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]. The numbers add up to 0, so flat areas go black and only the edges remain.
  • box: every number is 1 / (w * h). It averages.

A kernel whose numbers add up to 1 keeps the brightness. A result that falls outside 0 to 255 is clamped, which is why the edge picture is dark.

The kernel is laid over each pixel as it is, not flipped (a correlation, like OpenCV's filter2D and Pillow's Kernel). For the usual symmetric kernels there is no difference.

Two kernels instead of one​

Many kernels are the product of a row and a column. A 5 by 5 Gaussian is a row of 5 numbers and the same column. Giving the two instead of the product costs 5 + 5 multiplications per value and not 5 * 5, and the cost grows with the sum of the sides and not with the area. The binomial row 1 4 6 4 1 over 16 is the classic cheap approximation of a Gaussian, and the example prints how close it is. For the real one, gaussian_kernel(sigma) gives the row of a Gaussian of the standard deviation sigma, to use as both kernels, and gaussian_blur does it for you.

Gradients​

A gradient says how fast the values change, which is where the edges are. sobel and scharr return two pictures, the change to the right (dx) and the change downwards (dy), as float images that can be negative. A step of height 1 gives 4 with Sobel and 16 with Scharr, the one with the heavier smoothing across. magnitude combines them into the strength of the edge, the square root of dx squared plus dy squared. Canny, on the filters page, is made from these.

sobel, scharr and magnitude return and take NumPy float32 arrays, so they need pip install "libstb[numpy]".

A kernel with an even width or height has no center and is rejected: a ValueError, as is a kernel with more than one channel.

The edge​

As for every filter, edge says what is read past the border: clamp (the default), reflect, mirror, wrap or zero.

API at a glance​

A kernela list of lists of numbers
Convolvestb.convolve(img, kernel, edge=)
Row and column kernelsstb.convolve(img, row, col)
The taps of a Gaussianstb.gaussian_kernel(sigma, radius=0)
Gradientsdx, dy = stb.sobel(img), stb.scharr(img)
Strength of the edgestb.magnitude(dx, dy)