Dark marks near a pill's edge can come from contamination, curved-surface shading, reflections, or the background entering the inspection region. A dark-pixel threshold cannot distinguish those causes by itself. For teams commissioning pill-surface inspection, the fastest useful change is a controlled lighting comparison, followed by threshold validation on varied samples. Start with the image formation problem, then separate localization, stain detection, and rim coverage into checks you can verify independently.
1. Diagnose the false-positive pattern before changing thresholds
Check the common causes in the following order. Keep the original grayscale images, inspection regions, and detection overlays together so each decision can be traced back to its input.
| Symptom | Likely cause | Discriminating test | First corrective action |
|---|---|---|---|
| Dark crescent follows one side of most pills | Directional shading on the curved surface | Illuminate from the opposite direction | Compare diffuse illumination with the directional setup |
| False marks cluster outside or across the outline | Localization error or background inclusion | Overlay the inspection region on every sample | Correct the region before adjusting detection sensitivity |
| Dark regions change when the pill moves slightly | Reflections or background interaction | Translate the same pill while keeping camera settings fixed | Change illumination geometry or background presentation |
| Broad regions appear after image normalization | Frame-dependent scaling or uneven illumination | Compare raw images against processed images | Remove automatic scaling during diagnosis |
| Thin outlines appear after reference subtraction | Registration mismatch | Overlay the aligned boundaries | Improve registration before interpreting residuals |
A useful first experiment repeats the same good pill at several positions and orientations. If a dark patch stays tied to the camera-facing edge rather than the physical surface, illumination is a strong suspect. This is evidence, not proof: real marks can also change appearance with viewing geometry.
For contour-shaped errors produced by reference comparison, use the checks in reducing contour artifacts in image subtraction. Do not compensate for a registration error by making the stain threshold less sensitive.
2. Compare illumination geometries under controlled conditions
Start with dome lights when a pale, curved pill develops dark edge crescents under directional illumination. Their broad angular illumination can reduce shading, but may also reduce contrast from shallow surface defects.
Use bar lights as a controlled comparison. Opposing directions help reveal whether a candidate region depends strongly on the illumination angle. They are also useful when a dome cannot fit around the inspection position.
| Setup | What it helps reveal | Main limitation | Evidence to collect |
|---|---|---|---|
| Diffuse dome | Stain contrast with reduced directional shading | Camera opening and incomplete coverage can remain visible in reflections | Center-to-rim brightness and stain contrast |
| One diffused bar | Direction-dependent shading and surface relief | Curvature can create a strong dark side | Location of false regions relative to the light |
| Opposing bars, captured separately | Changes caused by illumination direction | Requires repeatable positioning or image registration | Whether candidates persist, move, or change contrast |
| Opposing bars, illuminated together | More balanced directional coverage | Specular reflections and residual shading can remain | Worst-case appearance across the pill population |
Lock exposure, gain, aperture, and image processing during each test series. Between setups, adjust illumination output, where permitted, to produce a comparable unsaturated clean-surface brightness. Record every change rather than letting automatic exposure conceal differences.
The dome-light geometry guide explains angular coverage and camera-opening effects. The glare-control approach for plastic lid inspection also helps when a glossy coating or packaging creates bright reflections.
3. Select trial parts by geometry, not housing size alone
A dome must illuminate the relevant curved surface throughout the allowed part movement. Its external dimensions do not establish the useful inspection field. Check the emitting opening, camera sightline, mounting clearance, and position of the pill relative to the illuminated interior.
The LS-DOM-0085 and LS-DOM-0062 are dome candidates for a geometry review. Confirm coverage and mechanical compatibility from their drawings before selecting a trial part.
- Size
- 100-200 mm
- Voltage
- 24 V
- Size
- 100-200 mm
- Voltage
- 24 V
For the directional comparison, the LS-BAR-1276 is a diffused bar candidate. Confirm its suitability for the intended field, mounting arrangement, and exposure through a sample evaluation.
- Size
- 200-400 mm
- Type
- Diffused
- Voltage
- 24 V
Use the lighting finder to narrow the available geometries. Check driver compatibility, permitted operating mode, connectors, and cable arrangement separately; a matching supply voltage alone does not establish electrical compatibility.
4. Check whether the smallest stain has enough pixels
Threshold tuning cannot recover a stain that occupies too few pixels. Establish the smallest required stain, the inspection field, and the camera's usable pixel count before comparing algorithms.
For a first estimate, assume a locally flat surface and approximately uniform image scale:
Suppose an illustrative setup covers a field width of 40 mm across 1600 pixels:
An approximately circular stain with that diameter covers about 50 pixels geometrically, because its area is approximately π × 4². The thresholded area may be smaller because blur and low contrast soften the boundary.
Eight pixels across is an example, not a universal acceptance criterion. Required sampling depends on contrast, focus, motion, and the permitted miss rate. Verify the smallest real defect at the worst field position, not only at the image center.
Curvature also foreshortens features near the visible rim. If the acceptance specification includes the sidewall, an overhead image may not provide adequate coverage regardless of nominal pixel count.
5. Tune detection against measured contrast, not one image
First compare a fixed threshold against a locally referenced threshold using the same stored images. Avoid changing illumination and processing parameters together; otherwise, the cause of any improvement becomes unclear.
A fixed threshold identifies pixels below an intensity limit. It is simple and repeatable when clean-surface brightness stays sufficiently consistent. It becomes unreliable when the clean rim is darker than a genuine stain near the center.
A locally referenced detector compares each pixel with an estimated neighborhood background:
Here, I is image intensity, B is the local background estimate, and T is the residual threshold. All three intensity quantities must use the same numerical scale.
Consider illustrative measurements from an 8-bit image set. Suppose clean central regions produce residuals of 2–6 gray levels, clean rim regions reach 14, and required stains produce 12–22. No single residual threshold cleanly separates those overlapping populations.
If a lighting change reduces the clean rim maximum to 7 while required stains remain at 12 or above, a threshold of 9 becomes a candidate for validation. It is not yet a production setting: independent samples must confirm the separation.
Choose the background-estimation scale relative to defect size. For a stain about 8 pixels wide, a 25-pixel neighborhood is a reasonable trial, not a guaranteed solution. A neighborhood that is too small follows the stain and suppresses its residual. A larger one may include the pill boundary and create a false dark band.
Exclude background pixels from the estimate or use a boundary-aware method. For broader parameter selection, the guide to scratch detection and dynamic thresholding explains related contrast and neighborhood tradeoffs.
6. Separate localization, central inspection, and rim coverage
Find the pill outline independently of the stain threshold wherever possible. Otherwise, a dark stain can change the inspection region that should contain it, creating a circular dependency.
Overlay the localization result before inspecting detection blobs. Check pills at the smallest and largest expected apparent sizes, tilted positions, and allowed placement extremes.
A practical design uses separate regions:
- Central surface: inspect with the validated fixed or local threshold.
- Rim band: inspect with a method validated specifically for curvature and foreshortening.
- Outside background: exclude it from surface-stain decisions, while retaining it for relevant placement checks.
For example, reducing a region inward by 0.15 mm creates an excluded band about 6 pixels wide at the earlier sampling. That may suppress boundary artifacts, but it also removes genuine inspection coverage. Record the excluded band in the acceptance specification rather than describing it as fully inspected.
When using separate opposing-light images, register them before comparing candidates. Do not average them immediately: averaging can suppress a real mark that is clear in only one exposure. Likewise, angle-dependent appearance alone is insufficient reason to discard a candidate.
The live binary inspection preview guide provides a useful way to visualize region and threshold changes during commissioning.
7. Validate the chosen setup across the production envelope
Build separate tuning and holdout sets. The holdout set must remain unused until the lighting geometry, region rules, and thresholds are fixed.
Include variation that can change the image without representing an unacceptable stain:
- Pill color, coating gloss, curvature, embossing, and score lines.
- Position, rotation, height, and expected focus variation.
- Background appearance and, where applicable, packaging reflections.
- Lighting warm-up and expected ambient-light variation.
- Required defect sizes, contrasts, and positions, particularly near the rim.
Use quality-approved defect labels. Artificial marks can help study contrast, but they do not establish performance on real contamination or coating defects.
Report false rejects and misses separately. For example, 6 false rejects among 1000 known-good presentations gives 6 / 1000 × 100 = 0.6%. A separate defective set might produce 2 misses among 100 known-defective presentations, or 2%. These illustrative rates answer different questions and should not be merged into one accuracy figure.
Record whether trials represent independent physical samples or repeated presentations of the same samples. Repetition measures presentation sensitivity; it does not provide equivalent evidence about manufacturing variation. Even zero observed errors does not establish zero future error probability.
Verify that every required image is acquired and processed within the available cycle. If the inspection participates in automated rejection, test missing images, stale decisions, and reject tracking under the machine's documented fault-handling design.
Use the lighting stability test procedure to check drift after the geometry is selected. For pharmaceutical use, inspection acceptance, validation, and change control must follow the applicable quality process; image contrast alone does not identify a contaminant or establish compliance.
8. Check the decision before ordering or deployment
A dome is not automatically the right answer. Directional illumination may preserve useful contrast that diffuse illumination removes. A mixed strategy may be necessary when the same station must inspect stains, embossing, and surface damage.
Before committing, complete this checklist:
- Required defect defined: specify minimum size, contrast, location, and acceptance criteria.
- Coverage documented: identify any rim or sidewall region the camera cannot inspect reliably.
- Lighting comparison saved: retain raw images from each geometry with acquisition settings.
- Mechanical fit checked: verify camera access, part clearance, mounting, and allowed movement.
- Electrical compatibility confirmed: review the light, driver, trigger, and permitted operating mode together.
- Processing regions reviewed: confirm that background rejection does not silently exclude required defects.
- Holdout performance recorded: report misses and false rejects with their sample counts.
- Recovery behavior verified: define the response to missing images and invalid inspection decisions.
Do not use stronger smoothing or frequency filtering merely because the binary image looks cleaner. Any filter that removes background texture can also remove a defect with similar spatial dimensions.
Start the lighting configurator with the field size, smallest stain, available clearance, and comparison images. If stain and shadow contrast still overlap, send those requirements through applications support before committing to hardware or a threshold strategy.
Questions
Is a dome light always best for detecting pill stains?
A dome is a useful starting point when directional lighting creates dark crescents on curved pills. It is not automatically the final choice. Compare actual stain contrast, rim coverage, and reflections against directional illumination using the same representative samples and controlled camera settings.
Why does local thresholding still detect clean pill edges?
Local thresholding compensates for some slow brightness variation, but curved edges and background pixels can distort its neighborhood estimate. If clean-edge residuals overlap genuine stain residuals, changing the threshold only trades false rejects against misses. Improve illumination or region handling before further tuning.
Can the pill rim simply be excluded from inspection?
An inward margin can keep background and uncertain boundary pixels out of central-surface inspection. However, that margin becomes uninspected unless another validated method covers it. Express the excluded width in physical units, check placement variation, and confirm that the acceptance specification permits the resulting coverage.
How many pixels should the smallest stain cover?
There is no universal pixel requirement because contrast, blur, curvature, and processing all affect detection. Estimate pixels across the smallest stain from field size and image width, then validate real defects at the least favorable location. Do not use geometric blob area alone as evidence of reliable detection.
How many samples are needed to validate the lighting?
Use independent good and defective samples that span expected variation, with a separate holdout set for the final decision. Report false rejects and misses with their denominators. Required sample counts depend on the acceptable error rates and confidence requirements established by the applicable quality process.


