Sub topic 2
Kernels and Convolution with `cv2.filter2D`
Assume you know basic Python, NumPy indexing and dtypes, pixels, and grayscale images. You should also have OpenCV installed and be able to read an image. This chapter explains the operation behind many filters: applying a small matrix, called a kernel, across an image.
The working model
A grayscale image is a two-dimensional array. Each value represents a pixel intensity, commonly from 0 to 255. A kernel is another, much smaller array of weights.
At each image location, the kernel is placed over a neighborhood of pixels. OpenCV multiplies each kernel value by the corresponding pixel, adds the products, and writes the result at the center location.
For a 3 × 3 kernel, the calculation is:
output(x,y)=\sum_{i=-1}^{1}\sum_{j=-1}^{1}K(i,j)I(x+j,y+i)In mathematical convolution, the kernel is flipped before the operation. cv2.filter2D uses correlation by default, so it does not flip the kernel. This distinction matters for directional kernels, such as edge detectors. It does not matter for symmetric kernels, such as a centered blur.
Applying a kernel
This example builds a 5 × 5 averaging kernel. Every weight is 1/25, so the output becomes the local average of 25 pixels.
import cv2
import numpy as np
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5, 5), dtype=np.float32) / 25.0
blurred = cv2.filter2D(
gray,
ddepth=-1,
kernel=kernel,
borderType=cv2.BORDER_REFLECT_101,
)
print(gray.shape, gray.dtype)
print(blurred.shape, blurred.dtype)The ddepth=-1 argument keeps the source depth. Since gray is usually uint8, the result is also uint8. For kernels that produce negative values, use a signed or floating-point output depth instead. Otherwise, negative results can be clipped or lost.
A kernel's sum often predicts its behavior:
| Kernel sum | Typical effect |
|---|---|
| 1 | Preserves average brightness |
| Greater than 1 | Raises average intensity |
| 0 | Responds mainly to changes, such as edges |
| Less than 1 | Reduces average intensity |
A blur kernel sums to 1. A simple horizontal edge kernel might contain positive weights on one side and negative weights on the other, giving it a sum near 0.
Border handling
The kernel extends beyond the image at the edges. OpenCV must invent or reuse values for those missing pixels. This choice is the border mode.
Common modes include:
cv2.BORDER_CONSTANT: pads with a constant value, often black.cv2.BORDER_REPLICATE: repeats the nearest edge pixel.cv2.BORDER_REFLECT: mirrors pixels around the boundary.cv2.BORDER_REFLECT_101: mirrors without repeating the boundary pixel.
Border choices can create bright, dark, or artificial edge responses. Use a mode that matches the image and inspect objects near the frame boundary.
A directional example
This kernel emphasizes a change from dark pixels on the left to bright pixels on the right:
edge_kernel = np.array(
[[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]],
dtype=np.float32,
)
response = cv2.filter2D(gray, cv2.CV_32F, edge_kernel)The CV_32F output preserves both positive and negative responses. The sign indicates the direction of the intensity change. Later, gradient magnitude can discard that sign when only edge strength is needed.
Exercise
Why should an averaging kernel have weights that sum to 1, and why is CV_32F useful for the directional kernel?
Show answer
A sum of 1 preserves the local average brightness. CV_32F preserves negative and fractional filter responses that uint8 cannot represent safely.