Sub topic 2
Kernels and convolution with cv2.filter2D
This chapter assumes you can write basic Python, index NumPy arrays, and have OpenCV (cv2) installed. It also assumes you know that a grayscale image is a 2D uint8 array and a color image has a third channel axis in BGR order. Everything later in this tutorial (smoothing, sharpening, gradients) applies a small array of weights to an image. Learn the mechanism here once.
What a kernel is
A kernel is a small array of numbers, usually 3×3, 5×5 or another odd size. It is also called a filter or mask. To filter an image, you slide the kernel over every pixel. At each position, you multiply the kernel's weights by the pixels beneath them and add up the products. That sum becomes the output pixel at the kernel's center.
For a 3×3 kernel k and an image f, the output at row y, column x is:
out[y, x] = sum over i, j in {-1, 0, 1} of k[i, j] * f[y + i, x + j]The kernel's values decide what the filter does. Equal positive weights that sum to 1 average the neighborhood, so the image blurs. Weights that subtract the left side from the right side respond to vertical edges.
The kernel then moves one pixel and the process repeats. The result is a new image of the same height and width.
Correlation versus convolution
Mathematical convolution flips the kernel by 180° before sliding it. The formula above does not flip, so it is technically cross-correlation. cv2.filter2D computes correlation. For symmetric kernels such as box and Gaussian, the two give identical results. For asymmetric kernels, they differ. This script shows it with an impulse, a single bright pixel.
import cv2
import numpy as np
impulse = np.zeros((5, 5), np.float32)
impulse[2, 2] = 1.0
k = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], np.float32)
corr = cv2.filter2D(impulse, -1, k)
conv = cv2.filter2D(impulse, -1, cv2.flip(k, -1)) # flip both axes
print("filter2D (correlation):")
print(corr[1:4, 1:4])
print("true convolution:")
print(conv[1:4, 1:4])The first printout is the kernel rotated by 180° (9 8 7 / 6 5 4 / 3 2 1). The second reproduces the kernel as written. Filtering an impulse returns the kernel (flipped or not), which is why the kernel is also called the impulse response.
The signature
dst = cv2.filter2D(src, ddepth, kernel, dst=None, anchor=(-1, -1),
delta=0, borderType=cv2.BORDER_DEFAULT)| Parameter | Meaning |
|---|---|
| `src` | Input image, one or more channels. |
| `ddepth` | Output depth, such as `cv2.CV_32F`. `-1` means same as the input. |
| `kernel` | A single-channel floating-point array (`float32` or `float64`). |
| `anchor` | Kernel position that sits over the output pixel. `(-1, -1)` means the center. |
| `delta` | A value added to every result before it is cast to `ddepth`. |
| `borderType` | How to invent pixels beyond the image edge. |
Three details matter in practice.
- The kernel has one channel. On a color image,
filter2Dapplies the same kernel to each channel independently. To use different kernels per channel, split the channels withcv2.splitfirst. - The kernel should be float. An integer array may be accepted, but a
float32kernel is the safe habit. It avoids integer division surprises when you writenp.ones((5, 5)) / 25. - Odd sizes keep a clear center. An even-sized kernel has no center pixel, so the anchor becomes ambiguous and the output shifts by half a pixel.
Normalizing the kernel
The sum of the weights controls overall brightness. A kernel whose weights sum to 1 keeps the average brightness unchanged. A box filter is the standard case:
import cv2
import numpy as np
gray = np.tile(np.linspace(0, 255, 64, dtype=np.uint8), (64, 1))
ones25 = np.ones((5, 5), np.float32)
averaged = cv2.filter2D(gray, -1, ones25 / 25.0) # sums to 1: brightness kept
too_bright = cv2.filter2D(gray, -1, ones25) # sums to 25: saturates to 255
print(gray[32, 10:14], averaged[32, 10:14], too_bright[32, 10:14])Without the division by 25, every pixel above about 10 clips to 255, and the output is a white image with a thin dark strip at the left. Kernels used for edge detection often sum to 0 instead. On a flat region the output is 0, and only changes in intensity produce a response.
Output depth and saturation
With ddepth=-1 on a uint8 image, each result is rounded and clipped to the range 0 to 255. This is called saturation. It is the right behavior for smoothing, where the result always stays in range. It is wrong for derivative kernels, because negative responses become 0 and large positive ones become 255.
import cv2
import numpy as np
step = np.full((6, 6), 200, np.uint8)
step[:, 3:] = 50 # bright left half, dark right half
sobel_x = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]], np.float32)
as_uint8 = cv2.filter2D(step, -1, sobel_x)
as_float = cv2.filter2D(step, cv2.CV_32F, sobel_x)
print(as_uint8[2]) # [0 0 0 0 0 0]
print(as_float[2]) # [ 0. 0. -600. -600. 0. 0.]The edge goes from bright to dark, so the true response is negative. The uint8 result loses it completely. The float result keeps both its sign and its magnitude.
You can also use delta to shift a signed response into the visible range. With uint8 output, delta=128 places zero response at mid-gray. Responses beyond ±128 still clip.
Border handling in brief
Near the edge, part of the kernel hangs outside the image. filter2D fills those missing pixels according to borderType. The default, cv2.BORDER_DEFAULT, is BORDER_REFLECT_101, which mirrors the image around the edge pixel without repeating it. A later chapter compares the modes. For now, note that BORDER_CONSTANT pads with zeros, which darkens a blurred image along its edges. The reflecting modes do not.
Cost and kernel size
The work per pixel grows with the number of kernel entries. A 3×3 kernel needs 9 multiplications per pixel and a 31×31 kernel needs 961. OpenCV switches to a frequency-domain (DFT) method for large kernels, so very large kernels are not as slow as the count suggests. Many useful kernels are also separable. A 2D kernel is separable if it equals the outer product of a column vector and a row vector. In that case, cv2.sepFilter2D applies the two 1D kernels in turn, which is much cheaper. Box and Gaussian kernels are separable, and OpenCV's dedicated blur and GaussianBlur already use this trick.
Common errors
- Using a kernel of integers and dividing with
/in a way that produces zeros, such asnp.ones((5, 5), np.uint8) // 25. Usefloat32and true division. - Forgetting that the result is clipped when
ddepth=-1, as shown above. - Expecting flipped-kernel convolution from an asymmetric kernel.
- Passing a 3-channel kernel and expecting per-channel behavior. Kernels are always 2D.
- Using an even kernel size and getting a half-pixel shift.
Exercise
You apply the kernel np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], np.float32) to a uint8 image with cv2.filter2D(img, -1, kernel) and see mostly black output. What two things explain this, and what change fixes the problem?
Show answer
The kernel's weights sum to 0, so flat regions give 0 (black), and only intensity changes respond. Its negative responses are also clipped to 0 because ddepth=-1 keeps the uint8 type. Pass cv2.CV_32F as ddepth, then convert for display with cv2.convertScaleAbs or cv2.normalize. The flat areas will still be dark, which is correct for this kernel.
Exercise
A 5x5 kernel of ones, divided by 25, is applied to a uint8 image. How does the output change if you forget to divide by 25, and why?
Show answer
The weights sum to 25 instead of 1, so each output pixel is about 25 times the local average. Everything above roughly 10 saturates at 255, and the result is nearly all white. Normalizing so the weights sum to 1 keeps overall brightness unchanged.