Computer vision
Sampling, Resizing, Filtering, and Morphology
Understand aliasing, interpolation, filtering, thresholding, and morphology as measurement transformations with explicit assumptions.
By the end you can
- Explain how sampling and interpolation affect edges, texture, and small objects
- Distinguish smoothing, sharpening, denoising, and morphological operations
- Recognize when preprocessing creates leakage or removes task evidence
- Design controlled ablations for classical image transformations
Comparison
Resizing is an estimator, not a neutral copy
Interpolation methods trade sharpness, smoothness, speed, and aliasing behavior. Nearest neighbor copies the closest sample and preserves discrete label values. Bilinear and bicubic estimate new samples from a neighborhood. Area or antialiased reduction aggregates the source support before producing fewer samples.
The name of the method is not the whole choice. Take one identical set of 1024x1024 FFHQ face images, resize them down to 299x299 with different library implementations, and compare each result against PIL-bicubic. The images are the same images, so FID should come out near 0. PIL-bilinear adapts its prefilter width to the downsampling factor, and scores FID 0.64. The fixed-width prefilters used by PyTorch and TensorFlow score 4.3 — close to naive nearest-neighbour subsampling at 7.4, which does no filtering at all. Parmar and colleagues ran that comparison in 2021. Nothing changed between the runs except which library performed the resize.
The paper names the cause in one sentence: “However, commonly-used implementations use a fixed-width prefilter, resulting in aliasing artifacts.” The four method names in this map are a first-order description. Underneath them sits a second choice: whether the prefilter adapts to the downsampling factor. The library makes that choice. It usually does not record it.
Nearest neighbor
Copies the nearest sample without averaging.
- Preserves discrete label values
- Creates blocky intensity images
- Useful for masks
- Risk: jagged boundaries
Bilinear
Interpolates from nearby samples with linear weights.
- Fast and smooth
- Common for photographs
- Blurs very small structures
- Risk: aliasing when downsampling
Bicubic
Uses a larger neighborhood and cubic interpolation.
- Often sharper than bilinear
- More computation
- May overshoot near edges
- Useful for display-oriented resizing
Area or antialiased reduction
Aggregates source support before producing fewer samples.
- Better for downsampling
- Reduces high-frequency aliasing
- Can erase tiny objects
- Requires task-aware scale checks
Downsampling can invent patterns
When high-frequency image structure is sampled too coarsely, different patterns can produce the same reduced samples. Fine stripes may become false waves. And a one-pixel defect may vanish.
Low-pass filtering before you downsample limits aliasing. But it also removes detail. The correct trade-off depends on the smallest evidence the task must preserve.
Deep networks inherited the problem rather than solving it. Richard Zhang put it flatly in 2019: “commonly used downsampling methods, such as max-pooling, strided-convolution, and average-pooling, ignore the sampling theorem”. The consequence is that “small input shifts or translations can cause drastic changes in the output”. The remedy is the classical one. Low-pass filtering before downsampling is “the well-known signal processing fix”. But inserting it naively does not work: the preprint says it “degrades performance”, the published version says it “leads to performance degradation”, and both mean the same thing. Placed carefully instead, the same filter raised “accuracy in ImageNet classification, across several commonly-used architectures”. The signal processing had been known for decades. Where to put it had not.
The same sampling failure has a visible face, one that people looked at for years without naming it. StyleGAN2 produced “texture sticking” — detail glued to screen coordinates rather than to the depicted surface. Tero Karras and six co-authors at NVIDIA and Aalto University found where it came from in 2021: “We trace the root cause to careless signal processing that causes aliasing in the generator network.” They reinterpreted every internal signal as continuous and filtered accordingly. The result matches StyleGAN2's FID and is fully equivariant to translation and rotation at subpixel scales. The fix was signal processing, not more capacity.
Antialiasing prevents false structure; it does not guarantee retention of tiny evidence.
Visual
Filters answer different questions
This map separates common operations by the information they emphasize: smoothing filters reduce local variation to suppress noise or small texture, edge and derivative filters respond to directional intensity change, sharpening filters increase local contrast by amplifying high-frequency components, adaptive or edge-preserving filters use local structure to limit boundary blur, and learned restoration estimates the transformation from data and inherits the training distribution.
What none of these families guarantees is that information removed from the picture has been removed from the model. Standard CNNs can predict a patient's self-reported race from medical images, at AUC 0.91-0.99 on x-rays, 0.87-0.96 on chest CT and 0.81 on mammography. Gichoya and colleagues reported that in the Lancet Digital Health in 2022. The obvious proxies did not account for it: body-mass index reached AUC 0.55, disease distribution 0.61, breast density 0.61. So they filtered the images in the frequency domain. Low-pass filtering only degraded performance around diameter 10, by which point the images were already visibly destroyed. High-pass filtering left performance high up to diameter 100, where the radiologist co-authors could not tell the image was an x-ray. The Results section says it plainly: “A high performance (up to diameter 100) in the absence of discernible anatomical features was maintained with the addition of a high-pass filter (ie, model performance was maintained despite extreme degradation of the image visually).”
A filter is chosen to remove something. What counts as removed is defined against the human eye, and the model is not the human eye. “The image looks unusable now” is not evidence that the evidence is gone.
Smoothing filters
Reduce local variation to suppress noise or small texture.
Edge and derivative filters
Respond to directional intensity change.
Sharpening filters
Increase local contrast, often by amplifying high-frequency components.
Adaptive or edge-preserving filters
Use local structure to reduce noise while limiting boundary blur.
Learned restoration
Estimate transformations from data and inherit the training distribution.
Example
Morphology treats foreground as geometry
Binary and grayscale morphology can be useful when the structuring element matches a real geometric assumption. The way to find out whether it matches is to measure it.
The most standard morphological assumption is that only the largest connected component is real. nnU-Net treats it as a hypothesis rather than a cleanup step. Isensee and colleagues built the system, described in Nature Methods in 2020, to configure preprocessing and post-processing automatically across 23 public biomedical segmentation datasets. It keeps non-largest-component suppression only if that raises the mean foreground Dice on cross-validation without lowering the Dice of any individual class. The rule is one line: “Whether to apply this postprocessing is determined by monitoring validation performance after cross-validation.” Standard practice has to earn its place on each dataset. Otherwise it does not get applied.
- Erosion: Removes foreground near boundaries and can separate thin connections — including connections the task needed to keep.
- Dilation: Expands foreground and can bridge nearby gaps, including gaps that were real separations between objects.
- Opening: Erosion followed by dilation removes structures smaller than the chosen element, whether or not those structures were noise.
- Closing: Dilation followed by erosion fills small gaps or holes, and cannot distinguish an artifact from a hole that is the evidence.
- Connected components: Converts a binary mask into candidate regions for counting or filtering; nnU-Net accepts the largest-component rule on a dataset only when cross-validation shows it raises mean foreground Dice and lowers no individual class.
Analogy
Editing a map with brushes of fixed shape
Someone cleans a paper map using a round eraser and a square stamp. Features smaller than the tool disappear or expand according to the tool's geometry.
The marks on the map are semantic objects, while morphology operates on chosen intensity or mask conventions. The scale assumption is the same on both sides: a tool's geometry decides which features survive. What the eraser cannot tell you is whether the specks it removed were dirt or the smallest towns on the map. nnU-Net's answer is the only one available — try it both ways and read the score.
A structuring element encodes a geometric prior that must match the task.
Key idea
Preprocessing can leak labels or future information
A crop centered using a human annotation can make training easy while being unavailable at inference; a threshold tuned on test images can transfer information from the evaluation set into the pipeline.
Every transformation that depends on data statistics, annotations, or later timestamps belongs inside the appropriate training or deployment boundary.
The leak can also be stamped into the pixels by the acquisition chain, before anyone writes a preprocessing step. Pneumonia-screening CNNs were trained on 158,323 chest radiographs drawn from three hospital systems. The abstract's “Methods and findings” reports what those networks had actually learned to see: “CNNs were able to directly detect hospital system of a radiograph for 99.95% NIH (22,050/22,062) and 99.98% MSH (8,386/8,388) radiographs.” Zech and colleagues published that in 2018. Pneumonia prevalence differed sharply between the sites: 34.2% at MSH against 1.2% at NIH. So merely sorting radiographs by hospital system reached AUC 0.861 on the pooled data. Nothing in the model code is wrong. The internal test set rewards a model for reading the stamp.
A preprocessing step can invalidate evaluation even when the model code is untouched.
Case
Leakage reached 294 papers across seventeen scientific fields
How often does data leakage actually happen? Kapoor and Narayanan went and counted. Their survey, published in Patterns in 2023, reports “17 fields where leakage has been found, collectively affecting 294 papers”, and introduces “a detailed taxonomy of eight types of leakage, ranging from textbook errors to open research problems”. Textbook errors are in that list, alongside problems nobody has solved. The failure sits in the pipeline around the model. That is why reading the model code never finds it.
Version discipline matters even here. The preprint of the same survey counts 329 papers and says “errors” where the published version says “leakage”. The published figures are the ones quoted above.
Steps
Evaluate a preprocessing operation with an ablation
Use controlled experiments, not which output looks better, to decide whether a transformation belongs in the pipeline. State the intended effect and name the artifact or invariance the operation should address. Define the vulnerable evidence — the small objects, thin boundaries, colors or textures the operation might damage. Compare matched pipelines with data splits, model, seed plan and evaluation protocol held constant. Inspect slice changes on both the target conditions and unaffected reference conditions. Save the exact parameters: kernels, interpolation modes, thresholds, and library behavior.
nnU-Net is what that procedure looks like once it is automated. Across 23 public biomedical segmentation datasets, the largest-connected-component step is not applied because it is standard practice. It survives on a given dataset only when cross-validation shows it raises the mean foreground Dice and lowers no individual class Dice. The same test is available for a resize mode, a blur radius or a threshold. And the fifth step is not bureaucracy: FID 0.64 against 4.3 on identical images is the size of the difference an unrecorded library choice can make.
1. State the intended effect
Name the artifact or invariance the operation should address.
2. Define vulnerable evidence
List small objects, thin boundaries, colors, or textures that might be damaged.
3. Compare matched pipelines
Hold data splits, model, seed plan, and evaluation protocol constant.
4. Inspect slice changes
Measure both target conditions and unaffected reference conditions.
5. Save exact parameters
Version kernels, interpolation modes, thresholds, and library behavior.
Thresholding converts intensity into a decision
A global threshold assumes comparable illumination and measurement scale across the image; adaptive thresholds use local neighborhoods, which can help under uneven lighting but may amplify local noise.
Thresholding should be evaluated as a classifier with false positives, false negatives, and uncertain boundary cases. A clean-looking mask is not enough.
There is a public benchmark that does exactly this. The 2018 Data Science Bowl set is 841 two-dimensional microscopy images with 37,333 manually annotated nuclei, from 31 experiments and 22 cell types, released as Broad Bioimage Benchmark Collection accession BBBC038. Caicedo and colleagues, writing in Nature Methods in 2019, scored 3,891 teams against a reference pipeline built in CellProfiler from classical thresholding and watershed. Precision, recall and F1 were computed from true positives, false positives and false negatives at stated coverage thresholds. At an IoU threshold of 0.5 the best model reached F1 0.889 against 0.819 for the classical reference, and 85 challenge algorithms beat that reference outright. The classical pipeline was not worthless. It was measured, and its distance from the field was a number rather than an impression. The paper gives the reason a fixed parameter cannot carry the task: “And even under controlled experimental conditions, no single parameter choice can segment all images correctly, because classical algorithms can fail to adapt to the heterogeneity of biological samples or can be sensitive to technical artifacts”.
Visual neatness can conceal systematic classification error.
Example
Fixtures for detecting silent image-operation changes
Small deterministic tests can catch library or configuration changes before they alter a dataset. Take the FFHQ resize again: PIL-bilinear at FID 0.64, the fixed-width prefilters of PyTorch and TensorFlow at FID 4.3, on identical images resized to 299x299. That gap is what an unpinned resize call costs when nothing in the repository tests for it. And it appears in the evaluation numbers, not in the code review.
- Resize a checkerboard and compare exact output dimensions and antialiasing behavior — and pin which library performs the resize, since an adaptive prefilter and a fixed-width one do not return the same data.
- Transform a one-pixel line to verify whether thin structures survive each interpolation mode.
- Apply morphology to a known binary pattern and compare expected connected components.
- Feed a saturated gradient through normalization to verify clipping and range handling.
- Round-trip a mask through storage and confirm that class IDs remain discrete.
Key takeaways
- Interpolation methods estimate new samples. On identical FFHQ images resized to 299x299, PIL-bilinear scores FID 0.64, where the fixed-width prefilters of PyTorch and TensorFlow score 4.3 — close to unfiltered subsampling at 7.4.
- Antialiasing limits false patterns during reduction but may remove task-relevant detail. Zhang's low-pass fix had to be placed carefully to raise ImageNet accuracy instead of degrading it.
- Filtering, sharpening, and morphology encode assumptions about scale, noise, and geometry. Gichoya's high-pass images still carried race information to the model up to diameter 100, past the point radiologists could recognise an x-ray.
- Preprocessing that depends on labels, held-out statistics, or future data can leak information. So can the acquisition chain: Zech's CNNs identified the acquiring hospital system for 99.95% of NIH radiographs.
- Thresholding should be evaluated as a decision rule rather than judged by mask appearance. The CellProfiler reference on the 2018 Data Science Bowl set reached F1 0.819 at IoU 0.5, and 85 algorithms beat it.
- Deterministic fixtures and ablations make classical image operations reproducible. nnU-Net keeps largest-component suppression only when cross-validation Dice says to keep it.