A dark spot and a short dark line can be straightforward to detect until background texture produces similar shapes. Increasing the threshold may reveal the defect while also creating dozens of unwanted regions. Adding morphology can reduce those regions, but the wrong operation can erase the feature you need.
This workflow is for inspections where defects appear near a known image corner. You will define a repeatable inspection region, segment dark pixels, separate small structures from broad background regions, and filter connected components. The key decision is whether morphology cleans the detection mask or creates a separate mask of small-feature candidates.
1. Define the smallest defect before choosing an operation
Start with a written acceptance rule rather than a threshold value. Collect acceptable parts, obvious defects, and defects close to the rejection boundary. Include both compact specks and narrow marks, because their widths respond differently to morphology.
Record these requirements:
- Minimum speck diameter or area that must trigger rejection.
- Minimum mark width and length that must trigger rejection.
- Allowed defect location relative to the part, not just the image corner.
- Normal texture, printed features, shadows, and edges that must remain acceptable.
- Whether the output needs a presence decision, a count, or dimensional measurements.
A minimum area alone is insufficient. A narrow line can have substantial area while remaining vulnerable to an opening operation. For example, a 2-pixel-wide mark extending 20 pixels has an area of 40 pixels, yet a wider structuring element may remove it.
Use the image-sampling accuracy guide when setting the relationship between physical defect size and pixel coverage. Detection sampling and measurement accuracy are different requirements; neither follows from the camera's total pixel count alone.
2. Stabilize acquisition and locate the corner region
Keep lighting, exposure, focus, and part presentation repeatable before tuning segmentation. If acceptable texture changes brightness between captures, a threshold may alternate between missing defects and detecting the background.
Capture representative images with the intended acquisition settings. Where practical, finish adjustment with exposure and gain fixed. The guide to which pixels influence automatic exposure and gain explains why changing image content can change brightness unexpectedly.
Next, distinguish two situations:
- Fixed presentation: a rectangular image region consistently contains the inspection corner.
- Moving presentation: locate a stable part feature, then place the inspection region relative to it.
Do not assume that the upper-left image corner is always the upper-left part corner. Translation or rotation can move a normal edge into the inspection region, producing a large dark component.
Process an enlarged region around the final decision area where possible. Thresholding and morphology can behave differently at crop boundaries, so keep the processing boundary away from features being judged. Confirm the required padding experimentally with defects near every edge.
3. Create a dark-pixel mask and inspect it directly
For a grayscale image, a simple dark threshold selects pixels below an intensity limit. Use this as the baseline when illumination is even and acceptable material has a consistent brightness.
Here, I is image intensity, T is the threshold, and R is the binary dark-pixel mask. Confirm the comparison convention in your software, especially whether equality belongs to the selected region.
Automatic global thresholding can work when foreground and background form distinguishable intensity groups. It becomes less dependable when dark defects occupy very little of the image or when shadows dominate the intensity distribution.
If brightness changes gradually across the part, compare global thresholding with local background normalization or adaptive thresholding. Choose a neighborhood larger than the defect being detected, then test broad defects as well. A local method can mistake a broad dark defect for its own background.
Display the raw image beside the binary mask. The live binary-image preview workflow is the closest companion to this procedure: it helps reveal whether failure starts in segmentation or in later filtering.
Save threshold masks for borderline samples. If the smallest required defect is already absent from R, no connected-component filter can recover it. Return to contrast, sampling, or threshold selection instead.
4. Use opening as a separator, not an automatic cleanup
Binary opening consists of erosion followed by dilation using a structuring element. It removes structures that cannot accommodate that element and can alter boundaries of larger regions.
There are two different ways to use its output:
| Approach | Mask sent to component analysis | Main purpose | Main risk |
|---|---|---|---|
| Direct threshold | Original dark mask | Preserve all segmented features | Texture remains as candidates |
| Opening as cleanup | Opened dark mask | Remove small foreground structures | Small defects disappear |
| Opening residual | Original mask minus opened mask | Extract small or narrow dark structures | Texture and boundary fragments also appear |
For small dark-defect detection, the residual can be useful because the features removed by opening are retained in a separate candidate mask.
B is the structuring element, O is the opened mask, and C contains foreground pixels present in R but absent from O. This is binary set subtraction, not grayscale background correction.
Consider an isolated speck spanning about 5 pixels and an opening element measuring 9 × 9 pixels. If the speck cannot contain that element, opening removes it from O. Subtracting O from R therefore places the speck in C.
A short line narrower than the element can also enter C, even when its total area is large. This is why element dimensions must follow defect width and orientation, not area alone.
The residual is not a perfect small-object selector. Large regions can contribute boundary fragments, narrow branches, or corners changed by opening. A defect merged with a broad dark background may also become incomplete. Compare R, O, and C on the same sample before trusting the final overlay.
Do not add dilation merely to make the overlay easier to see. Draw a thicker display outline instead. Dilation changes area and can merge neighboring defects; if used for detection, treat it as a separate, validated processing stage.
5. Label components and filter them in a controlled order
Run connected-component labeling on the chosen candidate mask. Specify connectivity explicitly: 4-connectivity joins edge-sharing pixels, while 8-connectivity also joins diagonal neighbors. Diagonal contact can therefore change the reported count.
Apply filters in an order that makes rejected candidates easy to explain:
- Position: retain candidates inside the valid part-relative inspection area.
- Area: remove regions below the validated minimum, without assuming every small region is harmless.
- Width and length: distinguish compact spots from narrow marks using suitable shape measurements.
- Boundary relationship: separate expected part edges from unexpected interior features.
- Intensity evidence: check the original grayscale pixels when shape alone cannot distinguish texture from defects.
Use separate acceptance branches for specks and marks. A circularity requirement suitable for compact spots can reject the elongated defect you also need to find. Likewise, an upper area limit can accidentally discard a large genuine defect; route oversized regions for rejection or review instead.
For physical area reporting, see measuring defect area and perimeter. Measure from a validated mask, not from a dilated display overlay.
Remember that component count is not automatically defect count. One physical mark can fragment during thresholding, while two nearby specks can merge into one region.
6. Work through a sampling and morphology example
Assume a hypothetical inspection image spans 80 mm horizontally across 4000 pixels. These are application assumptions, not operating specifications for a particular camera.
The camera finder can help shortlist acquisition hardware after you establish the required sampling. Use the calculator to explore a different field width or minimum feature size.
At this sampling, a mark 0.06 mm wide and 0.30 mm long spans approximately 3 × 15 pixels. Its ideal rectangular area is 45 pixels, but blur, threshold choice, and pixel alignment will change the segmented area.
A 9 × 9 opening element would remove an isolated, fully segmented mark of that width from the opened mask. The residual would retain it. However, a preliminary 3 × 3 opening could damage a borderline feature before the residual stage even begins.
Start by comparing the direct threshold mask against one residual configuration. Add operations only when saved failure cases demonstrate a benefit. If texture and required defects share the same size and shape, morphology alone cannot separate them; improve contrast or introduce another discriminating feature.
7. Choose acquisition and processing hardware separately
Area scan cameras suit workflows where you need access to acquired images and control over the processing sequence. Check image format, acquisition timing, and the software interface before selecting a camera.
LS-CMR-0166 is an area scan option to review. Confirm its suitability against your sampling, motion, and integration requirements rather than assuming the example above establishes compatibility.
- Sensor format
- 1/1.7"
- Interface
- USB3
- Resolution
- 12 MP
- Shutter
- Rolling
Smart cameras may suit inspections performed on the device. Before choosing that architecture, verify that the actual software supports the required thresholding, region subtraction, component measurements, and intermediate-image diagnostics.
LS-SMC-0063 is a smart camera option to evaluate. Its catalog listing alone does not establish support for this complete processing sequence.
- Interface
- GigE
- Resolution
- Up to 3 MP
Where centralized processing is needed, review vision controllers against the acquisition interfaces and processing workload. The machine-vision components guide explains the wider acquisition and control chain.
Do not replace hardware merely because the first threshold fails. Save original images and establish whether the limitation is contrast, sampling, processing support, or execution time.
8. Verify the workflow before release
Build a validation set containing normal texture, minimum-size specks, thin marks, large defects, and defects touching the decision boundary. Include the presentation and brightness variation expected during production.
Run a repeatable check:
- Freeze the processing settings and test images not used for tuning.
- Record missed defects and false rejects separately for each defect class.
- Review the raw image, threshold mask, opened mask, residual, and final accepted components for every failure.
- Measure total processing time under the intended acquisition load, including image transfer and diagnostic storage.
- Repeat after a restart to confirm that acquisition settings and inspection parameters are restored correctly.
For an initial challenge set, you might include 30 acceptable samples, 30 minimum-size specks, and 30 thin marks. Those 90 samples can expose obvious failure modes, but they do not establish a low production escape rate. Set final validation quantities from the inspection risk and required confidence.
Before ordering or releasing the station, confirm this short checklist:
- The smallest required defect remains visible in the original image and threshold mask.
- Morphology preserves it in the mask actually used for decisions.
- Normal edges and texture have an explicit handling rule.
- Location filters follow the part when its position changes.
- Reported dimensions come from calibrated sampling and a validated measurement mask.
- Saved images make false rejects and misses traceable.
When normal texture is indistinguishable from defects, return to image formation rather than adding more filters. The scratch-inspection lighting and thresholding guide explains how illumination can create separation before segmentation.
Start a hardware shortlist with the camera configurator, or send representative acceptable and defective images through applications support to discuss sampling and processing requirements.
Questions
Will opening erase the dark specks I need to detect?
Opening removes foreground structures that cannot accommodate its structuring element. If you inspect only the opened mask, small defects may disappear. An opening residual subtracts that opened mask from the original threshold mask, retaining removed structures as candidates. Validate the residual because normal texture and altered boundaries can appear there too.
How should I choose the morphology element size?
Convert the minimum defect width into pixels, then compare structuring elements against both compact specks and narrow marks. Size alone does not establish suitability: orientation, neighboring regions, and boundary effects matter. Start with the original threshold mask as a baseline and keep examples showing what each proposed element removes.
Can one component filter detect both specks and short lines?
Use separate shape criteria for compact and elongated defects, then combine their pass or reject decisions. A circularity filter can exclude valid dark marks, while a length requirement can exclude small spots. Shared position and intensity checks can still apply to both branches when validated against representative samples.
Do I need adaptive thresholding for dark speck detection?
A fixed threshold is worth testing when exposure, illumination, material brightness, and presentation remain consistent. Consider normalization or a local threshold when brightness varies across the inspection area. Neither approach replaces adequate contrast, and local methods need testing on broad defects that could influence their background estimate.
Can this workflow run on a smart camera?
Check the device's documented processing tools and diagnostic access before selecting it. The workflow needs more than thresholding: it may require binary set subtraction, configurable morphology, component measurements, and intermediate-mask inspection. Confirm those capabilities with representative images rather than inferring them from the camera's resolution or interface.

