Article sections
Where can classical image processing still be the best choice?Denoising, filtering and contrast: what are we correcting?Choosing fixed, Otsu or adaptive thresholdingWhat does morphology do, and when does it distort measurements?Edge detection, contours and geometric featuresDesigning a classical image processing pipelineWhy is one threshold not always enough for defect detection?Why does processing order affect the result?Edges, contours and connected components: what is the difference?Frequently asked questionsWhere can classical image processing still be the best choice?
Classical methods generally apply explicit rules to structural cues such as intensity differences, edges, shape, location, texture and geometric relationships. They can be highly efficient in industrial environments where lighting and part position are controlled.
Backlighting, for example, produces a dark part silhouette against a bright background. If the task is simply to locate its center or diameter, thresholding and contour analysis are worth trying before a complex learned model. The example below demonstrates the stages on a synthetic metal-part image; it is not a validated production-line result.

Each stage answers a specific question. Thresholding selects candidate object pixels. Morphology removes small noise components. Contour analysis locates the outer boundary or internal holes. Finally, fitting a circle or line extracts geometric properties. A visually pleasing mask does not necessarily produce the most accurate measurement; check against reference geometry.
What makes a good first prototype?
Start with the shortest practical chain rather than stacking dozens of filters. Every operation transforms information and can introduce measurement bias. Save input images, intermediate results, parameters and final measurements together so that unexpected changes can be traced to their origin.
Denoising, filtering and contrast: what are we correcting?
A Gaussian filter smooths high-frequency variation. It can reduce sensor noise and small local irregularities, but also blurs edges. A median filter can suppress isolated bright or dark points. A bilateral filter smooths while preserving some edges, at higher computational cost. CLAHE and similar local contrast methods can reveal detail, but may also amplify noise.
Avoid the vague goal of making the image clearer. A 9-by-9 Gaussian filter might remove the very 0.2 mm edge notch being inspected. Evaluate kernel size together with physical image scale. If the pixels-per-millimeter ratio changes, a previously suitable kernel covers a different physical area.
Practical recommendation: Evaluate each filter using at least two measures: its effect on detection or segmentation, and the displacement of the edge or measurement relative to a reference. Do not assume a better-looking image is better for measurement.
Choosing fixed, Otsu or adaptive thresholding
Thresholding divides pixels into foreground and background according to a rule. The simplest approach makes intensities above a threshold white and the rest black. A fixed threshold can work when lighting is stable and the classes have distinct intensity distributions. Uniform illumination, however, is not always achievable.
Otsu's method estimates a threshold from the histogram when suitable two-class intensity distributions exist. It is not a remedy for every lighting problem. Adaptive thresholding calculates local thresholds and can accommodate illumination gradients, but may also segment background texture as defects. Test parameters on difficult examples as well as clean images.

The number of white pixels is not enough to evaluate segmentation. Defect dimensions, preservation of internal holes, object fragmentation and stability near boundaries are more informative. In particular, a measurement mask and a defect-detection mask may require different settings.
What does morphology do, and when does it distort measurements?
Morphology applies structural operations to image shapes. Two basic operations are erosion and dilation. Erosion shrinks white foreground regions; dilation expands them. Opening applies erosion followed by dilation and can remove small bright components. Closing can fill small dark gaps. OpenCV morphological operations.

This can help inspection but threaten measurement. Closing may shrink a hole whose diameter is measured from the mask; erosion may reduce a part's measured external diameter. Recognize that morphology changes boundaries and validate settings against physical references. Choose kernel size according to the defect's pixel dimensions, not arbitrarily.
Edge detection, contours and geometric features
Producing a binary mask is only one step. Edge points, lines, circles, rectangles, moments and connected components can describe shape numerically.
Sobel and Scharr estimate the direction and rate of intensity change. Canny produces edge candidates through denoising and thresholding stages. The Hough transform searches for parametric geometry such as lines and circles. Contour analysis can extract closed foreground boundaries, perimeter, area and moments. OpenCV's documentation emphasizes the importance of a suitable binary foreground representation. OpenCV contours.
A flange hole rarely yields a perfect circular contour: shadows or glare may hide part of the edge. In such cases, robust geometric fitting, such as an appropriately configured RANSAC-like outlier-resistant approach, may outperform treating every pixel equally. Still verify that the circle or ellipse model represents the part's actual geometry.
Define the measurand first. Does hole diameter mean equivalent-area diameter, the smallest enclosing circle, fitted-circle diameter or distance along an axis? These need not agree on rough, oval or partially occluded parts.
Designing a classical image processing pipeline
A good classical system consists of small, individually validated operations rather than one powerful operator. A typical sequence stabilizes acquisition, suppresses noise, separates the object, removes small components with morphology, extracts geometry and applies a decision rule. Recording each output makes the first failing stage easier to identify.
Which information should a filter preserve?
Gaussian smoothing reduces high-frequency noise but can soften thin lines. Median filtering can remove isolated bright or dark points while altering narrow geometry. Bilateral filtering preserves some edges at additional cost. The best filter preserves the physical feature under inspection, not necessarily the smoothest-looking image.
| Operation | Benefit | Risk |
|---|---|---|
| Gaussian | Reduces some random noise | Can suppress fine edges and scratches |
| Median | Can reduce isolated salt-and-pepper points | May remove small real defects |
| Otsu thresholding | Automatic histogram-based threshold | Struggles with uneven lighting and multimodal distributions |
| Adaptive thresholding | Adapts to local brightness | Sensitive to local window and offset settings |
| Morphological opening | Can remove small foreground components | May erase small real defects |
| Morphological closing | Can connect narrow gaps | May shrink holes and bias measurements |
Why is one threshold not always enough for defect detection?
Changing illumination direction can alter the brightness of healthy metal faster than that of a defect. One intensity threshold may not separate the entire surface. Background subtraction, local contrast and shape priors can improve stability. As appearance variation becomes more complex, however, classical tuning becomes costly and should be compared with learned approaches.
Which contour features are useful?
Area, perimeter, aspect ratio, convexity, hole count and minimum-area bounding rectangles are simple but useful features. A gasket's internal-hole-to-outer-area ratio may indicate manufacturing defects. Yet pixel area is not physical area when orientation changes; geometric correction is needed for measurement.
Measure the defect's typical pixel width first. Applying a 5-by-5 structuring element to a scratch only two or three pixels wide can remove it. Do not enlarge morphological kernels without inspecting their effect on real defects.
Why does processing order affect the result?
A median filter followed by thresholding can remove small noise points. Reversing the order processes newly formed binary shapes differently and can change the result completely. Understand each step's physical assumption rather than accepting a visually pleasing output.
If a tiny hole is a manufacturing defect, closing can conceal it. A cleaner mask is not success. Measure sensitivity on actual defect examples and document the effects of product variation, lighting and minimum defect size in an experiment matrix.
Edges, contours and connected components: what is the difference?
Edge detection emphasizes abrupt intensity changes, without guaranteeing closed or continuous boundaries. Contour extraction usually follows the boundary of an existing binary mask. Connected-component analysis labels connected pixel groups. These methods address different questions and are not interchangeable.
Counting hole components in a closed backlit silhouette can provide a simple, traceable missing-hole check. Local scratches may be better described by gradient and orientation features. For a circular measurand, fitting a circle to the contour can be more appropriate than treating bounding-box width as diameter, though burrs and missing edges still affect the fit.
What should be checked before making the algorithm more complex?
Compare raw good and bad images of the same part side by side. If the difference is not visible, revisit optics and lighting before adding filters. If it disappears during masking, investigate preprocessing and thresholds. If masks are correct but decisions are wrong, check geometry and tolerance rules. This separation can greatly reduce debugging time.
Frequently asked questions
When can Otsu thresholding fail?
Uneven illumination or poorly separated foreground and background intensities can cause problems.
What is the difference between erosion and dilation?
Erosion tends to contract the selected foreground boundary; dilation expands it. The structuring element affects the result.
Classical methods or deep learning?
Classical methods can be advantageous when explicit rules separate the cases clearly. Broad appearance variation may require learning-based methods.
Technical references
This article combines explanations supported by technical references with educational numerical examples. The example system values are not measurements from an actual facility.