LightingTroubleshooting

Glass bottle defect detection: fix lighting before thresholding

Fix glass bottle defect detection by testing lighting, checking binary polarity, registering reference images and using absolute grayscale differences.

LumaSpec Vision10 min read Share on LinkedIn

On this page 10 sections
  1. 011. Establish whether the defect is visible before processing
  2. 022. Match the lighting experiment to the defect
  3. 033. Freeze geometry, exposure and motion
  4. 044. Treat binary polarity as a representation choice
  5. 055. Register reference images instead of merely resizing them
  6. 066. Compute absolute grayscale differences without clipping
  7. 077. Work through a numerical inspection example
  8. 088. Diagnose the remaining failure signature
  9. 099. Validate the decision before ordering hardware
  10. 10Questions

A black bottle shape on a white binary image is not automatically a processing failure. The real question is whether the original grayscale image separates the defect from acceptable glass. For transparent bottles, reflections, refraction and background structure often dominate that difference. Start with controlled lighting, then stabilize the geometry and compare registered images. This sequence helps you distinguish an optical problem from a thresholding or subtraction error before changing the inspection algorithm.

1. Establish whether the defect is visible before processing

Inspect the original image at a fixed display scale. Identify the defect location from an independently confirmed defective sample, rather than guessing from the processed image. Compare that location with equivalent regions on acceptable bottles.

If the defect disappears into reflections or background texture, a different threshold cannot reliably recover it. Improve acquisition before adding filters or more complicated segmentation.

Start with these checks, in order:

  1. Replace the scene behind the bottle with a uniform background that covers the entire inspection field.
  2. Fix the camera and bottle position, with the viewing direction approximately perpendicular to the inspected side.
  3. Exclude uncontrolled room light and reflections from nearby machinery.
  4. Lock exposure, gain and image processing settings during comparisons.
  5. Capture acceptable and defective bottles under each proposed lighting arrangement.

Use the same grayscale display limits for every image. Automatic contrast stretching can make an insignificant fluctuation look dramatic, or hide a meaningful brightness change.

The controlled image tests for apparent lens scratches provide a useful companion method for separating scene defects from contamination and optical artifacts.

2. Match the lighting experiment to the defect

Do not choose a background color independently of the illumination geometry. A bright, uniform backlight is useful for silhouettes. A dark, nonreflective enclosure can help surface features stand out under oblique illumination.

Inspection target First lighting trial What to examine Main limitation
Missing material at an outer edge Backlight behind the bottle Changes in the silhouette Internal structure and refraction may confuse the boundary
Scratch or chip on a visible surface Oblique spot illumination Local scattering or a changed reflection Visibility depends strongly on angle and bottle rotation
Feature visible only from some directions Sequential lighting directions or additional views Whether contrast persists across expected poses Additional images require timing and separate validation

For silhouette trials, begin with backlights. The illuminated region must cover the bottle's inspected outline throughout its allowed movement, not merely at its nominal position.

The LS-BKL-1468 is a red flat backlight candidate for these trials.

BacklightsFlat Backlight, 150 x 150 mm, Red (LS-BKL-1468)LS-BKL-1468
Size
100-200 mm
Type
Standard
Voltage
24 V
$389.00View partBuild a system with it

Compare diffuse and collimated illumination if the apparent edge moves with lighting geometry. The LS-BKL-0830 is a collimated backlight candidate. Collimation controls illumination direction; it does not remove the bottle's refraction or replace suitable imaging optics.

Backlights120 x 120 mm Collimated back light (LS-BKL-0830)LS-BKL-0830
Size
100-200 mm
Type
Collimated
Voltage
24 V
$309.00View partBuild a system with it

The comparison of collimated and diffuse backlighting explains that selection in more detail.

For surface trials, position spot lights so that direct reflections largely miss the lens while the defect redirects some light toward it. This is the principle behind dark-field illumination, although curved glass can still create bright reflections elsewhere.

Bright-field and dark-field lighting geometry High-angle light reflects off the flat surface straight into the lens, so the surface looks bright. Low-angle light reflects away from the lens, so the surface looks dark and only edges or scratches scatter light upward.flat part with a scratchCamerabright field(high angle)dark field (low angle)flat areas reflect away;only the scratch sends light up
Bright-field and dark-field lighting geometry. High-angle light reflects off the flat surface straight into the lens, so the surface looks bright. Low-angle light reflects away from the lens, so the surface looks dark and only edges or scratches scatter light upward.

The LS-SPT-0162 is a white spot light candidate for this experiment.

Spot lightsSpot light, 24 mm dia., White (LS-SPT-0162)LS-SPT-0162
Size
Under 50 mm
Voltage
24 V
$349.00View partBuild a system with it

Try several illumination directions, recording the geometry for each. For example, compare incidence angles of approximately 30°, 45° and 60° relative to the camera axis. These are experimental starting points, not universal inspection settings.

Use the lighting finder once the successful geometry is known. Polarizers may reduce selected reflections, but curved surfaces, polarization changes and stressed glass can limit their usefulness. Test them rather than assuming they will remove every highlight.

3. Freeze geometry, exposure and motion

Reference subtraction assumes that acceptable bottles produce similar images. Conveyor vibration, bottle rotation, fill level, labels and illumination drift can violate that assumption before the arithmetic begins.

Use a repeatable presentation and inspect a defined region. Keep lens focus, aperture, working distance and exposure unchanged between reference and production images. A background seam crossing the bottle can become a stronger feature than the defect.

For moving bottles, estimate exposure from the permitted object-space blur:

maximum exposure time = permitted blur / object speed

Suppose the speed is 400 mm/s and the permitted blur is 0.05 mm:

t = 0.05 mm / 400 mm/s = 0.000125 s = 125 microseconds

This estimates motion blur only. Available light, sensor noise and readout behavior still need checking. Rolling shutters can also distort moving objects; shortening exposure alone does not necessarily remove that distortion.

Compare shutter and interface requirements through area scan cameras and the camera finder. Confirm trigger and illumination timing from the selected hardware documentation. The external-pulse camera triggering guide helps separate exposure timing from sustainable acquisition rate.

Avoid automatic exposure changes during reference comparison. The exposure-region feedback troubleshooting guide explains how changing image content can disturb brightness control.

4. Treat binary polarity as a representation choice

A threshold divides intensities into classes. It does not decide which class represents defective material.

For a bright backlight, much of the background may exceed the threshold while the bottle boundary remains darker. Displaying the bottle as black and the background as white can therefore be entirely correct.

bright_mask = I > T dark_mask = I <= T

These masks have opposite polarity but contain the same partition information. Choose the polarity expected by the next operation, then label foreground and background explicitly.

A whole-image threshold can also emphasize the wrong population. A large bright background may dominate the histogram while a small scratch barely affects it. Restrict analysis to the inspection region and inspect grayscale profiles through known defects before selecting a threshold method.

The live binary image preview guide covers interactive mask checking. Here, the acceptance test is stricter: the defect must remain distinguishable across acceptable bottle variation, not simply look convincing in one binary preview.

5. Register reference images instead of merely resizing them

Matching image dimensions does not align bottle features. Two equally sized arrays can still contain translated, rotated or differently magnified bottles.

Start by finding stable features, such as an intact neck section or a fixture landmark. Estimate the permitted geometric transformation, apply it to the current image, and compare only the overlapping valid region.

Use the simplest transformation that matches the mechanics:

  • Translation for small horizontal and vertical positioning changes.
  • Translation and rotation when orientation varies within a controlled range.
  • Scale adjustment only when a real magnification change exists and the measurement consequences are understood.

Do not register using the suspected defect itself. An overly flexible transformation can reduce the very difference you need to detect. Similarly, stretching each bottle to the same outline can hide dimensional defects.

Interpolation during registration changes pixel values near edges. Establish the normal residual using registered acceptable bottles, not an untransformed reference alone.

A transparent curved bottle is not a flat printed target. Rotation can change refraction and reflections even after its outline is aligned. If those appearance changes dominate the defect signal, improve presentation, use multiple views, or inspect local features instead of forcing whole-image subtraction.

6. Compute absolute grayscale differences without clipping

Subtracting unsigned image arrays can discard negative differences, depending on the processing environment. For example, subtracting a reference value of 180 from a current value of 110 gives −70 mathematically. Saturating unsigned arithmetic may store zero instead.

Convert both images to a signed or floating-point representation before subtraction, then take the absolute value:

I_float = floating_point(current_grayscale) R_float = floating_point(reference_grayscale) I_aligned = register(I_float, R_float) D = abs(I_aligned - R_float)

These expressions are conceptual operations, not commands for a particular software package. Check the conversion behavior in your environment: some conversions preserve the original intensity range, while others normalize it.

For a darker feature, the absolute difference is:

abs(110 - 180) = 70

For a brighter feature at the same reference intensity:

abs(220 - 180) = 40

Both changes now remain visible. Keep the sign as a separate diagnostic image if darker and brighter changes need different interpretation.

Exclude invalid registration borders, fixture features and irrelevant background using a region mask. Set the mask from inspection geometry rather than from whichever threshold happens to produce a convenient shape.

7. Work through a numerical inspection example

Assume an inspected field spans 120 mm across 2400 image pixels. This is an illustrative application, not a specification for any named camera.

object sampling = field width / image width = 120 mm / 2400 pixels = 0.05 mm/pixel nominal defect width in pixels = 0.20 mm / 0.05 mm/pixel = 4 pixels

Four pixels across a feature is a useful feasibility check, not a detection guarantee. Contrast, focus, orientation and motion may still make that feature unreliable. The camera resolution calculation tool can help carry a sampling requirement into camera selection.

Camera resolution for the smallest feature
Units
Pixels needed
–
Sensor size
– MP
Smallest sensor that fits
–
Pixel on the part
– mm
Pixels across the feature, that sensor
–

Pixels needed = field / feature × pixels per feature on each axis (field incl. margin). The lens must resolve the pixels too: Nyquist = 1000 / (2 × pixel µm) lp/mm.

Find cameras with enough pixels Open the full calculator

Now consider alignment. A residual shift of one pixel corresponds to 0.05 mm in this example. That shift can create a bright difference band along much of the bottle outline, even when the bottle is acceptable.

Suppose trial data, retained on a common 0–255 intensity scale, show acceptable residuals mostly below 12 intensity levels. A confirmed defect produces a connected patch above 32 levels. A difference threshold of 18 levels is a reasonable experimental candidate between those observations, not a validated production setting.

Inspect the connected regions above that threshold. Record their area, location and maximum difference. A trial area limit of 6 pixels would suppress isolated pixels, but could also reject evidence from a very small real defect.

Repeat the calculation for every required defect class. Set the final threshold and region criteria from acceptable variation and confirmed defects, rather than transferring these example values directly.

8. Diagnose the remaining failure signature

After controlling acquisition and arithmetic, use the residual pattern to choose the next test. Avoid changing several settings together, because that obscures which correction helped.

Symptom Likely cause Discriminating test Corrective action
Defect absent in the original image Insufficient optical contrast Change illumination direction while keeping exposure fixed Select a geometry that reveals the defect
Broad differences across the bottle Exposure drift, pose change or different contents Compare background intensity and stable bottle regions Stabilize acquisition or separate product recipes
Double bands along most edges Registration error Overlay reference and current outlines Correct alignment and mechanical repeatability
Only brightening changes appear Signed differences lost during arithmetic Test subtraction on known numeric values Convert before subtraction and use absolute differences
Many tiny isolated regions Noise or overly low threshold Repeat captures of the same stationary bottle Improve signal quality and validate region filtering
A defect appears only at selected rotations Directional reflection or occlusion Rotate a confirmed sample through expected poses Add views or constrain presentation

If a stationary acceptable bottle changes substantially between captures, solve that repeatability problem before judging the defect algorithm.

9. Validate the decision before ordering hardware

Begin with a small, labeled feasibility set, such as 20 acceptable bottles and 10 confirmed defective bottles. This can expose major weaknesses, but it does not establish a production false-reject or missed-defect rate.

Keep a separate validation set that was not used to choose thresholds. Include different production batches, expected bottle positions and realistic conveyor speeds. Capture difficult acceptable examples, not only visually perfect bottles.

Before selecting hardware or releasing an inspection recipe, check that:

  • Each required defect is visible in the retained grayscale image.
  • The lighting covers the full inspection region and positioning range.
  • Exposure and readout behavior meet the motion requirement.
  • Registration does not remove the defect or distort its measurement.
  • Difference thresholds use a documented intensity scale.
  • Mask borders and excluded regions cannot hide required inspection areas.
  • Decisions use validated region criteria, not binary color alone.
  • Failure images and acquisition settings are retained for diagnosis.

A single side view is the wrong answer when the requirement includes hidden surfaces or defects obscured by overlapping glass walls. Additional directions, bottle rotation or a different inspection method may be necessary. Do not claim complete bottle coverage from one successful example.

Once the trials identify a repeatable lighting geometry, use the light configurator. For help translating defect size, field of view and motion into a testable setup, send representative images and inspection requirements through application support.

Questions

Does a black bottle on a white binary image mean thresholding failed?

Not necessarily. A bright background and darker bottle features can naturally produce that polarity. Confirm which binary value your subsequent operations treat as foreground. More importantly, check whether the required defect is distinguishable in the original grayscale image before deciding that the threshold is wrong.

Should glass bottle inspection use a backlight or a spot light?

Start with backlighting for silhouette changes such as missing material at an outer edge. Test oblique illumination for surface features that scatter light or alter reflections. Transparent glass can respond differently with rotation, so compare confirmed defects and acceptable bottles across the expected presentation range.

Why does resizing a reference image not make subtraction reliable?

Equal dimensions do not establish geometric alignment. Translation, rotation, magnification changes and different optical appearances can remain after resizing. Register stable features using a transformation justified by the mechanics, then evaluate residual differences on acceptable bottles before choosing defect thresholds.

How can image subtraction detect both darker and brighter defects?

Convert both grayscale arrays to a representation that preserves negative intermediate values before subtracting. Then take the absolute difference if either darkening or brightening can indicate a defect. Verify that conversion leaves both images on the same intensity scale, and exclude invalid registration borders.

Can one camera view inspect the entire glass bottle?

One view may support a narrowly defined inspection, but it cannot establish coverage of hidden surfaces. Curved walls can overlap in the image, while scratches and chips may appear only under selected directions. Define the required coverage first, then validate additional views or controlled rotation where necessary.