30 min read · Machine vision

Factory teams often pick the camera and the model first, then find that the defect they need to inspect barely shows in the image. No algorithm helps in that case, because the information was never in the image. Lighting decides whether a defect shows up as a dark shadow, a bright line, or blends into the surface.
This article uses a small simulator written in plain Python and numpy, with nothing extra to install. It shows how five kinds of lighting render five kinds of defect differently, measured as a single number, CNR (contrast-to-noise ratio). It then covers three things that often go wrong on site: ambient light, the use of strobes and filters, and over-bright images that lose data. Managers can read the tables and the summary. Developers can follow along and run every step.
This simulator is a learning tool, not a real optical simulation. It has no shadows, no inter-reflections and no lens. All numbers come from synthetic parts and from values we set ourselves (such as sensor sensitivity and ambient light). They only show the direction, which lighting is worth trying first. They do not tell you what value any particular light will give on your parts.
The real problem: same light, different defects, very different images
A glossy metal surface reflects light like a mirror. A matte surface scatters light in all directions. A scratch only slightly deep can disappear under direct light, yet stand out clearly when the light comes from a low angle at the side. The hole or edge of an opaque plate is usually measured most accurately when the light is behind the part. This difference comes from the basic laws of light reflecting off a surface. It is not about model or brand.
Consider three hypothetical situations. They are not projects of any BT San customer.
- A hypothetical metal parts plant: inspecting thin scratches on a glossy surface. With coaxial light, the scratch is visible on only some parts, because a shallow scratch reflects back into the camera just like the surrounding surface. After switching to low-angle light from the side, the scratch becomes a clear bright line on a dark background.
- A hypothetical packaging line: reading print on a glossy label. The image has patches of glare from a dome light, so the operator raises the camera gain to brighten the image. The result is saturated pixels, and the contrast of the text disappears completely.
- A hypothetical assembly line: measuring the diameter of a hole in an opaque plate. With front light, the hole edge has a negative angle, so the measured size is off by several pixels. After moving the light behind the plate as a backlight, the edge is sharp and the size is stable.
These three cases are what the simulator in this article can reproduce, and they answer the same question: which lighting to try first, and what can break the result when you move from the lab bench to the conveyor.
What the documents and textbooks say
| Topic | What the source says | Effect on our simulator |
|---|---|---|
| Diffuse surface (Lambertian) | The brightness you see does not depend on the viewing angle. It varies with the cosine of the angle between the surface normal and the light direction. | Used as the diffuse term: kd times max(0, N·L) |
| Phong model | Combines a diffuse part, a specular part and ambient light. The specular part varies with a power of R·V. | Used as the specular term: ks times max(0, R·V) raised to alpha |
| Dark-field lighting | Only light scattered by the sample into the lens is seen, so the scene is dark and the scattering parts are bright. | A ring light at a low 12-degree angle imitates this principle. A flat surface looks almost dark and a steep scratch looks bright. |
| Ambient light in machine vision | Lighting makers' manuals suggest 3 ways to handle ambient light: strobe, a light-blocking enclosure, and a bandpass filter. A filter conflicts with a color camera under white light. | Experiment 2 tries a strobe and a bandpass filter against ambient light that we set ourselves. |
| Measuring camera quality | The EMVA 1288 standard defines how to measure and report camera performance, such as signal-to-noise ratio. | We use a shot-noise and read-noise model with values we set ourselves. We do not follow the standard in full. |
The manufacturers' manuals and textbooks help you form a hypothesis, but no document can tell you which light your part needs. Always test with real parts.
Files in the example
| File | Purpose |
|---|---|
| scene.py | Builds 5 kinds of synthetic parts: a scratch, a bump, a dent, a hole in an opaque plate, and print on a glossy label |
| lighting.py | 5 kinds of lighting, rendering, exposure setting, capture with noise, and CNR measurement |
| demo.py | Runs all three experiments: lighting ranking, ambient light and excess gain |
| test_lighting.py | 7 unit tests |
| output.txt | The actual output of python3 demo.py |
| README.md | How to run it, and its limits |
Step 1: A part is a height map plus a surface color map
Each part has a height map (which gives the surface normal at each pixel). A kd map says how much the surface scatters light, and a ks map says how glossy it is. Two masks mark the defect area and the background area used for comparison. The first part is a scratch, a groove 1 pixel deep on glossy metal. The groove walls are rough, so they scatter light (high kd, ks of zero), while the surrounding surface is almost mirror-like.
@dataclass
class Case:
name: str
height: np.ndarray # surface height in pixel units (slope = tilt)
kd: np.ndarray # diffuse albedo map 0..1
ks: np.ndarray # specular strength map 0..1
alpha: float # specular sharpness (bigger = more mirror-like)
transmit: np.ndarray # fraction of backlight passing through, 0 for opaque
defect: np.ndarray # bool mask: the thing we want to see
bg: np.ndarray # bool mask: reference background (kept away from the defect)
true_diam: float = 0.0
def make_cases(seed=1):
rng = np.random.default_rng(seed)
one, zero = np.ones((N, N)), np.zeros((N, N))
cases = []
# 1) fine scratch on shiny flat metal: V groove 1 px deep (~22 degree flanks); the torn walls scatter light
d = np.abs(YY - (48 + 0.15 * (XX - 48))) / np.sqrt(1 + 0.15 ** 2)
wall = np.clip(1 - d / 2.5, 0, None)
h = _texture(rng, 0.12) - 1.0 * wall
cases.append(Case("scratch on shiny metal", h, 0.1 + 0.5 * (wall > 0), 0.9 * (wall == 0), 40, zero,
(d < 3) & (XX > 10) & (XX < 86), d > 8))Step 2: Five kinds of lighting as directions and weights
Each lighting type is a list of directions (azimuth and elevation angle from the surface) with weights that sum to 1, so total light power is the same when you compare. The dome uses 32 directions covering a half sphere. Coaxial is the same direction as the camera. The dark-field ring light uses four directions at a 12-degree elevation. The bar uses one direction at a 50-degree elevation. The backlight does not go through this formula. It uses a transmission map instead.
def unit(az, el):
az, el = np.radians(az), np.radians(el) # el = angle above the surface plane
return np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])
LIGHTS = { # name -> [(direction, weight)] ; weights sum to 1 so total power is comparable
"dome": [(unit(a, e), 1 / 32) for e in (25, 45, 65, 85) for a in range(0, 360, 45)],
"coaxial": [(V, 1.0)],
"dark-field ring": [(unit(a, 12), 0.25) for a in (0, 90, 180, 270)],
"bright-field bar": [(unit(0, 50), 1.0)],
}
ORDER = ["dome", "coaxial", "dark-field ring", "bright-field bar", "backlight"]def normals(h):
gy, gx = np.gradient(h)
n = np.stack([-gx, -gy, np.ones_like(h)], -1)
return n / np.linalg.norm(n, axis=-1, keepdims=True)
def render(case, light):
"""Noise-free signal, 1.0 = what a perfect white diffuser would give under a light at normal incidence."""
if light == "backlight":
from scene import blur
return blur(case.transmit, 1) # slight blur: light wrap at the edge
n = normals(case.height)
s = 0.0
for L, w in LIGHTS[light]:
ndl = n @ L
diff = np.clip(ndl, 0, None)
rz = 2 * ndl * n[..., 2] - L[2] # z of mirror direction = R . V
s = s + w * (case.kd * diff + case.ks * np.clip(rz, 0, None) ** case.alpha)
return s
Step 3: Set the exposure and capture with a noisy sensor
A real image is not clean. The simulator sets the exposure automatically so that the 99.5th percentile of the signal is at 0.92 of full scale (so it does not saturate), with a cap of 8 times. It then captures with Poisson shot noise plus Gaussian read noise, rounds to 8 bits and clips at 0 and 255. The full-well capacity of 4000 electrons and the read noise of 3 electrons are assumed values for an imaginary sensor.
def auto_exposure(s, target=0.92, cap=8.0):
"""Gain so the 99.5th percentile sits at `target` of full scale (no clipping), limited by `cap`."""
return min(cap, target / max(np.percentile(s, 99.5), 1e-6))
def capture(s, exposure, rng):
e = rng.poisson(np.clip(s * exposure, 0, None) * FULL_WELL) + rng.normal(0, READ_E, s.shape)
return np.clip(np.round(e / FULL_WELL * 255), 0, 255)
Step 4: Measure with a CNR that does not fool you
The CNR used is the mean difference between the defect and the background (measured from the noise-free image, already clipped at 8 bits), divided by the square root of the sum of squares of two terms. The first term is frame-to-frame noise (take two images, then take the standard deviation of their difference divided by the square root of 2). The second term is the surface texture of the background, which makes the image look cluttered. A floor value of 0.29 is used, or 1 divided by the square root of 12, which is the noise from 8-bit rounding. This also avoids dividing by zero. If more than half of the background is saturated at 255, CNR is NaN, because the number is no longer meaningful. For the hole case, the code also measures the diameter against the 40 pixels that was actually set.
def measure(case, s, exposure, rng):
"""CNR = mean |defect - background| (noise free, 8-bit clipped) / sqrt(temporal^2 + clutter^2)."""
clean = np.clip(255 * s * exposure, 0, 255)
contrast = np.abs(clean[case.defect] - clean[case.bg].mean()).mean()
a, b = capture(s, exposure, rng), capture(s, exposure, rng)
temporal = (a - b)[case.bg].std() / np.sqrt(2) # frame-to-frame noise
clutter = clean[case.bg].std() # surface texture seen as background clutter
sigma = max(float(np.hypot(temporal, clutter)), 0.29) # floor = 8-bit rounding noise 1/sqrt(12)
out = dict(contrast=contrast, sigma=sigma, sat=float((a >= 255).mean() * 100), bg=float(clean[case.bg].mean()))
out["cnr"] = contrast / sigma if (a[case.bg] >= 255).mean() < 0.5 else float("nan") # clipped background: CNR meaningless
if case.true_diam: # edge measurement: threshold midway, area-equivalent diameter
thr = (a[case.defect].mean() + a[case.bg].mean()) / 2
low = a[case.defect].mean() < thr
yy, xx = np.mgrid[0:a.shape[0], 0:a.shape[1]]
win = np.hypot(xx - 48, yy - 48) < 36
area = ((a < thr) if low else (a > thr))[win].sum()
out["diam_err"] = 2 * np.sqrt(area / np.pi) - case.true_diam
return outRun it and read the result
Run it with python3 demo.py. The output below is real and is stored in the file output.txt.
1) lighting ranked by CNR per defect (auto exposure, 8-bit, same light budget)
== scratch on shiny metal
# lighting CNR contrast noise sat% exposure
1 dark-field ring 100.5 154.2 1.53 0.00 6.52
2 bright-field bar 93.1 151.1 1.62 0.00 1.95
3 dome 23.8 82.1 3.45 0.00 2.04
4 coaxial 18.3 107.2 5.85 0.00 0.92
5 backlight 0.0 0.0 0.29 0.00 8.00
== embossed characters
# lighting CNR contrast noise sat% exposure
1 dark-field ring 37.5 58.2 1.55 0.01 6.49
2 coaxial 29.5 144.7 4.90 0.00 1.02
3 dome 26.3 112.2 4.26 0.00 3.48
4 bright-field bar 17.1 27.5 1.61 0.21 1.86
5 backlight 0.0 0.0 0.29 0.00 8.00
== dent on matte surface
# lighting CNR contrast noise sat% exposure
1 bright-field bar 7.5 27.3 3.65 0.01 1.24
2 coaxial 3.0 11.4 3.86 0.00 1.08
3 dome 2.0 8.0 3.93 0.00 1.46
4 dark-field ring 1.1 4.2 3.82 0.00 5.35
5 backlight 0.0 0.0 0.29 0.00 8.00
== hole edge on opaque plate
# lighting CNR contrast noise sat% exposure diam err px
1 backlight 809.0 234.6 0.29 0.00 0.92 -0.2
2 coaxial 59.7 231.8 3.88 0.00 0.71 +6.4
3 dome 58.2 230.6 3.96 0.00 1.37 -0.2
4 bright-field bar 50.8 178.4 3.51 0.21 1.33 +2.1
5 dark-field ring 43.2 119.9 2.77 0.00 3.37 -0.2
== print on glossy label
# lighting CNR contrast noise sat% exposure
1 dark-field ring 48.6 190.6 3.92 0.00 5.53
2 bright-field bar 48.6 189.4 3.90 0.00 1.49
3 backlight 43.3 170.7 3.94 0.00 2.63
4 dome 40.9 159.6 3.90 0.00 1.27
5 coaxial 30.5 117.3 3.85 0.00 0.71
2) ambient light leaking in (scratch, dark-field ring; ambient = a uniform veil of 120 DN at 8 ms, made up)
setup CNR contrast rel.contrast sat% flicker swing/contrast
no ambient (reference) 93.1 138.8 4.46 0.0 0.00
ambient, 8 ms continuous 27.6 87.0 0.58 5.3 1.10
ambient, 0.5 ms + 16x strobe 85.8 138.8 3.60 0.0 0.04
ambient, 8 ms + bandpass 88.5 138.8 3.74 0.0 0.03
ambient, 0.5 ms strobe+bandpass 93.4 138.8 4.41 0.0 0.00
3) too much gain (print on glossy label, coaxial light, exposure relative to auto)
gain x CNR contrast sat%
0.50 21.3 58.6 0.0
1.00 29.9 117.3 0.0
1.25 nan 108.5 90.6
1.50 nan 79.2 90.6
2.00 nan 20.5 90.6
4.00 nan 0.0 100.0- Scratch on glossy metal: the dark-field ring light gets a CNR of 100.5 and the bar 93.1, while the dome gets 23.8, coaxial 18.3, and the backlight 0 because an opaque plate lets no light through. A steep scratch scatters light into the camera, while the smooth flat surface reflects light out of the camera and so appears dark.
- Bump on glossy metal: dark-field still leads at 37.5, but coaxial at 29.5 is much closer. The soft edge of the bump keeps direct light usable.
- Dent on a matte surface: the result reverses. The bar gets the highest, 7.5, and dark-field gets only 1.1, because the matte surface already scatters light. Low-angle light does not make the dent stand out much. The whole row is low, which means this case is hard for every light in this model.
- Hole in an opaque plate: the backlight wins by a wide margin, with a CNR of 809.0 and a size error of -0.2 pixels. Coaxial gets a CNR of 59.7 but a size error of +6.4 pixels. A high CNR does not mean the size is measured correctly.
- Print on a glossy label: dark-field and the bar tie at 48.6, while coaxial is lowest at 30.5, because the glossy surface reflects straight back into the camera.
- Experiment 2 (ambient light): the reference row gets a CNR of 93.1, not the 100.5 in the first table, because it uses a different seed and exposure target. Adding a light veil of 120 DN (set by us) at 8 ms continuous, CNR falls to 27.6 and 5.3 percent of pixels saturate. A 0.5 ms strobe with 16 times more light gets 85.8. A bandpass filter gets 88.5. Using both gets 93.4, close to the reference.
- Experiment 3 (gain): the glossy label under coaxial light at a gain of 1x gets a CNR of 29.9. At 1.25x, 90.6 percent of the background saturates and CNR is NaN. At 4x the contrast drops to 0. An image that looks bright and pretty does not mean it can be inspected.
A takeaway you can use: the ranking of lights depends on the surface and defect pair. No light wins every row. These numbers give a direction in which to start experimenting. They are not measurements from anyone's real parts.
Testing with unittest
test_lighting.py has 7 tests that check the key principles of the simulator: a flat surface has its normals pointing up, a flat mirror is dark under dark-field but bright under coaxial, the backlight sees the hole but not the scratch, the exposure setting does not saturate and respects the cap, a saturated image destroys the contrast and makes CNR NaN, a capture is clipped to 8 bits and is repeatable with the same seed, and the ranking is ordered correctly (in the hole case the backlight wins).
def test_saturation_destroys_contrast_and_cnr_is_nan(self):
c = self.cases[4]
s = render(c, "coaxial")
e0 = auto_exposure(s)
ok = measure(c, s, e0, np.random.default_rng(1))
hot = measure(c, s, e0 * 4, np.random.default_rng(1))
self.assertLess(hot["contrast"], 0.1 * ok["contrast"])
self.assertGreater(hot["sat"], 90)
self.assertTrue(np.isnan(hot["cnr"]))
def test_ranking_is_sorted_and_hole_prefers_backlight_for_edge_size(self):
r = rank(self.cases[3])
self.assertEqual([x["cnr"] for x in r], sorted((x["cnr"] for x in r), reverse=True))
self.assertEqual(r[0]["light"], "backlight")
coax = next(x for x in r if x["light"] == "coaxial")
self.assertGreater(abs(coax["diam_err"]), 3) # chamfer fools front light
self.assertLess(abs(r[0]["diam_err"]), 1)
Run it with python3 -m unittest test_lighting in the example folder. All 7 passed when this article was written.
When you use it for real
The simulator helps you choose which light to try first, but the real decision has to come from real parts and a trial lighting kit. These are the things the example does not cover.
- Try real parts, both good and bad, in quantity, including parts from different lots with different surfaces, different colors and stains. Then try a trial lighting kit before you buy. Do not decide from brochure images.
- Color and wavelength: light of the opposite color to the background darkens the background, and light of the same color as the defect makes the defect blend in. A bandpass filter must match the light's wavelength, and lighting makers' manuals warn that a filter conflicts with a color camera under white light.
- Polarizers: glossy surfaces and clear plastic show glare. Crossed polarizers on the light and the lens reduce direct reflection, but the image gets darker and you must compensate with more light or longer exposure. This simulator does not model polarization.
- Strobe and synchronization: parts on a fast-moving conveyor need a short exposure time. The light must flash in step with the camera trigger. A small error in trigger delay shifts the image. See the article on global shutter for shutter speed.
- Heat and lamp aging: LED brightness drops with temperature and time. Allow some spare power and schedule light recalibration, or use a standard white plate in the image as a reference.
- Blocking ambient light: sunlight from a window or flickering ceiling lights make the image change over the course of the day. Experiment 2 uses a uniform veil of light, which is simpler than reality. An enclosure or a cover cloth is usually the cheapest first step.
- Resolution and field of view must also fit the lighting: a defect smaller than two pixels usually does not show, even with good lighting. See the article on lenses, resolution and FOV.
Adapting it to different businesses
- Metal plants and castings (hypothetical): scratches and burrs usually respond to low-angle light. For hole-size measurement, try a backlight first.
- Packaging makers (hypothetical): inspecting print on glossy film or cans. Try dark-field or a bar, and watch for excess gain that saturates the image.
- Electronics assembly (hypothetical): inspecting solder and connectors often needs lights from several angles in turn within one station. Plan the strobe timing and the time per part.
Common mistakes
- Choosing the camera before the lighting, then trying to fix an unclear image with an algorithm.
- Looking only at whether the image is pretty or bright, without measuring the contrast between the defect and the background.
- Raising gain or exposure time until pixels saturate, and thinking the image has improved.
- Experimenting in a fully enclosed lab, then using the result on a site with sunlight and ceiling lights.
- Using one type of light on a part that has several different surfaces in one piece, without trying several images with different lights in turn.
- Using a high CNR to decide a size measurement, when the edge may shift with the light angle. Check the size error separately.
- Forgetting that a missed inspection means both bad parts getting through and good parts being thrown away. See the article on false accept and false reject for the pass criteria.
Checklist before you lock the lighting
- Write down clearly the defect you need to see (type, smallest size, position) and the parts that must not trigger a false alarm.
- Prepare several good and bad parts from several lots, plus parts whose surface changes along the production line.
- Try at least three lighting types with a trial lighting kit, and capture the same set of parts with each.
- Measure the contrast between the defect and the background the way this example does, and check that no pixels are saturated.
- Test on site at every time of day. Try switching the factory lights on and off.
- If ambient light interferes, try an enclosure, a strobe and a filter, in order of cost.
- Record the position, distance, angle and settings of the light, and set a schedule for checking and replacing it.
Caveats of this example: no shadows, no inter-reflections, no real lens or blur, no polarization, no color. It uses five synthetic parts and assumed values for the sensor and ambient light. The lighting ranking is therefore only a starting point for experiments. Use it as a learning model, not as a tool for choosing lighting on a real production line.
References
- Advanced Illumination: A Practical Guide to Machine Vision Lighting (ambient light methods, pass filters) (accessed 2026-11-21)
- Keyence: Machine Vision Lighting Selection Guide (accessed 2026-11-21)
- Wikipedia: Dark-field microscopy (accessed 2026-11-21)
- Wikipedia: Lambertian reflectance (accessed 2026-11-21)
- Wikipedia: Phong reflection model (accessed 2026-11-21)
- EMVA: EMVA 1288 standard for characterization of image sensors and cameras (accessed 2026-11-21)




