Image filtering
图像滤波
Use tiny images to test smoothing, derivative signs, separability and the assumptions hidden at a boundary.
image-filteringA question to test
Imagine a tiny image containing just one grey pixel with value seven. Apply a normalized blur. Should it remain seven? It does if the image continues with that same value outside its boundary; it becomes darker if everything outside is assumed black. A filter’s coefficients alone do not specify its result.
Image filtering combines neighbouring measurements to smooth noise, estimate local changes or emphasize structure. The useful question is which information should survive. Averaging can suppress independent noise, but it also blurs a narrow line. A derivative reveals a change in intensity and can amplify noise. Before selecting a filter, specify the image representation, the intended measurement and the boundary rule.
The model and its derivation
Let be a scalar image and a kernel indexed around its centre. Let denote an explicitly extended image outside the observed rectangle. Correlation uses:
Convolution uses the opposite offset:
Flipping both kernel axes makes our correlation loop compute convolution. Symmetric blur kernels conceal this difference. The horizontal kernel does not: correlating it with the ramp gives one in the interior, whereas convolution gives minus one. OpenCV explicitly defines filter2D as correlation despite its name and some loose tutorial wording. Image Filtering: filter 2D — OpenCV 4.10.0
A weighted average with coefficients summing to one preserves a constant image wherever the extension also has that constant value. For independent, zero-mean noise of equal variance , its output variance is:
This follows by expanding the variance of a weighted sum: cross-covariances vanish under independence. It does not hold in this form when padding repeats the same noisy observation, because repeated samples are correlated.
Consider the separable binomial smoothing kernel:
It is Gaussian-like, but we are not claiming it is the exact sampled Gaussian for a specified standard deviation. A separable kernel factors as , allowing horizontal and vertical one-dimensional passes. Distributing the sums proves their equivalence to the two-dimensional operation under consistent extension. A K-by-K direct kernel on H-by-W pixels costs O(HWK²); two length-K passes cost O(HWK). This implementation holds an intermediate image, using O(HW) working storage for fixed K.
NumPy’s edge mode repeats boundary values. Its default constant padding supplies zeros; we name that choice zero in the teaching interface. Reflection is another possible assumption, and different libraries’ reflection conventions must be checked rather than guessed. numpy.pad — NumPy 1.26 Smoothing Images — OpenCV 4.10.0
Run a small experiment
The following complete program uses floating-point grayscale arrays, odd kernel dimensions and a centre anchor. separable computes correlation in both passes. It does not silently change integer image types or select a library-dependent border default. Run with Python 3.12 and NumPy 1.26.4.
import numpy as np
def filter2d(image, kernel, operation='correlation', padding='edge'):
a, k = np.asarray(image,dtype=float), np.asarray(kernel,dtype=float)
if a.ndim != 2 or min(a.shape,default=0) < 1 or not np.isfinite(a).all():
raise ValueError('image must be a finite nonempty 2D array')
if k.ndim != 2 or min(k.shape,default=0) < 1 or any(n%2==0 for n in k.shape) or not np.isfinite(k).all():
raise ValueError('kernel must be finite with positive odd dimensions')
if operation not in ('correlation','convolution') or padding not in ('edge','zero'):
raise ValueError('unknown operation or padding')
if operation == 'convolution':
k = k[::-1,::-1]
ry, rx = k.shape[0]//2, k.shape[1]//2
padded = np.pad(a,((ry,ry),(rx,rx)),mode='edge' if padding=='edge' else 'constant')
out = np.zeros_like(a)
for y in range(k.shape[0]):
for x in range(k.shape[1]):
out += k[y,x] * padded[y:y+a.shape[0],x:x+a.shape[1]]
return out
def separable(image, horizontal, vertical, padding='edge'):
h,v = np.asarray(horizontal,dtype=float),np.asarray(vertical,dtype=float)
if h.ndim != 1 or v.ndim != 1:
raise ValueError('separable factors must be vectors')
return filter2d(filter2d(image,h[None,:],padding=padding),v[:,None],padding=padding)
if __name__ == '__main__':
h=np.array([.25,.5,.25]); kernel=np.outer(h,h)
print('one pixel, edge:', filter2d([[7]],kernel).item())
print('one pixel, zero:', filter2d([[7]],kernel,padding='zero').item())
ramp=np.tile(np.arange(5,dtype=float),(5,1)); derivative=[[-.5,0,.5]]
print('correlation derivative:', filter2d(ramp,derivative)[2,2])
print('convolution derivative:', filter2d(ramp,derivative,operation='convolution')[2,2])
print('separable agrees:', np.allclose(filter2d(ramp,kernel),separable(ramp,h,h)))
one pixel, edge: 7.0
one pixel, zero: 1.75
correlation derivative: 1.0
convolution derivative: -1.0
separable agrees: True
For the one-pixel image, replicated padding makes all nine samples seven; the normalized weights preserve seven. Zero padding leaves only the centre contribution. Its weight is 1/4, producing 1.75. This is a boundary effect, not a broken normalization.
Tests compare direct and separable evaluation under both supported boundaries, including one-pixel and narrow images. A separate literal index calculation checks convolution with an asymmetric kernel. Other checks cover derivative sign, linearity, invalid shapes and nonfinite input. These are numerical checks of the stated operation, not an image-denoising benchmark.
Where the method breaks
Linear smoothing mixes across object boundaries. Median filtering can resist isolated extreme values but is nonlinear; the separability proof above does not automatically apply to it. Edge-aware smoothing uses additional criteria and can preserve some boundaries, at the price of more assumptions and computation. The OpenCV tutorial surveys several choices, while this program implements only fixed linear filters. Smoothing Images — OpenCV 4.10.0
A zero-sum derivative kernel rejects a constant interior, but padding can create an artificial boundary edge. Displaying negative derivatives in an unsigned image can also hide or wrap values. Keep the computation in a suitable numeric type, inspect its range, and make display scaling explicit.
Smoothing before reducing image resolution can reduce aliasing; merely taking every second pixel does not guarantee this. A filter suitable for removing high frequencies before downsampling may erase the small object you intended to detect. Check both the noise and the target scale. Our tiny array examples establish arithmetic, not the right kernel for every scene.
Exercises with answers
1. Why can a symmetric blur fail to expose a convolution/correlation bug?
Answer. Flipping a symmetric kernel leaves it unchanged. Use an asymmetric derivative kernel as a diagnostic.
2. What is the interior noise-variance factor for the two-dimensional binomial kernel?
Answer. A one-dimensional factor has squared-weight sum 3/8. The outer product gives (3/8)²=9/64, assuming nine independent input noise values.
3. Why is that factor wrong for a one-pixel image with edge padding?
Answer. Every padded sample is the same observation. The weighted sum equals that observation, so its noise variance is unchanged.
4. Compare direct and separable 9-by-9 filtering per interior pixel.
Answer. Direct evaluation uses 81 weighted contributions; two length-nine passes use 18. Actual timing also depends on memory access and implementation overhead.
Sources and next steps
The API reference fixes the exact correlation convention; NumPy fixes boundary semantics; the smoothing tutorial supplies context for choosing a filter. Image Filtering: filter 2D — OpenCV 4.10.0 numpy.pad — NumPy 1.26 Smoothing Images — OpenCV 4.10.0
Compare with convolution for the neural-network setting. Continue to edges and corners, where derivative products reveal whether a local patch constrains one direction or two.
Make a prediction, then check
Why does normalized filtering change a one-pixel image from 7 to 1.75 under zero padding?
Learning objectives
- Distinguish correlation from convolution using a derivative.
- Derive separable-filter cost and explain boundary effects.
Prerequisites & connections
Explore related knowledge →References
- Image Filtering: filter2D — OpenCV 4.10.0
OpenCV contributors - numpy.pad — NumPy 1.26
NumPy developers - Smoothing Images — OpenCV 4.10.0
OpenCV contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit camera, filter, descriptor and local-motion models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.
- Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
- 6 tests: direct/separable operations with both boundaries including narrow images, literal asymmetric convolution, derivative sign, linearity and invalid inputs. Derived independent-noise variance factor9/64 and explained its failure under replicated observations.
- Single AI author compared all six sections, formulas, examples, source scopes and four exercise/answer pairs across both languages.35 tests across six chapters passed before freezing; no independent human review claimed.
- Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
Source locations checked:
- Image Filtering: filter2D — OpenCV 4.10.0 · filter2D equation and kernel-flip/anchor paragraph.
- numpy.pad — NumPy 1.26 · mode definitions: constant, edge, reflect, symmetric.
- Smoothing Images — OpenCV 4.10.0 · Averaging and Gaussian filtering sections; no tutorial code copied.
Related topics