Contrast autofocus can produce a sharp image of the wrong surface, repeatedly reverse direction, or finish outside the inspection deadline. These symptoms need different fixes. Before changing search algorithms, record sharpness across the usable focus range while the scene and exposure remain fixed. This procedure helps you separate an unsuitable measurement window from unstable images, missed peaks, and actuator timing errors. It also establishes a reference against which you can judge a faster production search.
Match the symptom to a controlled test
Start by deciding what failed: selection of the intended depth, repeatability, or completion time. A high sharpness score does not prove that the inspection surface is in focus.
The broader autofocus and image stabilization explanation describes the different functions. Here, the objective is to diagnose the contrast-based feedback loop itself.
| Symptom | Likely starting point | First test |
|---|---|---|
| Background is sharp but the part is blurred | Measurement window contains competing depths | Move the window entirely onto the inspection surface |
| Focus repeatedly reverses around one setting | Score fluctuations, excessive correction, or inadequate settling | Hold focus stationary and measure score variation |
| Search stops at different depths | Multiple peaks or dependence on the starting position | Compare searches with a finely sampled sweep |
| Best score occurs at a search boundary | Range excludes the peak or scores remain misleading | Inspect images near the boundary before extending the range |
| Bench operation works but production fails | Scene motion, exposure changes, or stale frames | Repeat with a stationary part and fixed image settings |
Change one variable at a time. Save the images as well as the scores; otherwise, a misleading metric can look like successful focusing.
Establish a stable image baseline
Use these diagnostic steps before tuning the search:
- Stop the part, or hold a representative sample at its inspection position. Stop other motion that changes the measurement window.
- Fix exposure time, gain, illumination, and aperture where those controls are available. Record the settings rather than relying on startup defaults.
- Disable automatic sharpening, contrast adjustment, and other adaptive processing where supported. Keep the pixel format and image scaling unchanged.
- Hold the focus command constant and capture repeated images. Calculate the same sharpness metric for every frame.
- Associate each image with the focus setting that was actually settled when exposure occurred. Use documented control and acquisition behavior.
If a fixed-focus sequence already produces large score changes, the search algorithm is not the first problem. Investigate lighting variation, vibration, noise, clipping, or changing image content.
For example, suppose stationary scores range from 980 to 1,020, while adjacent focus positions differ by only 10 score units. A search cannot reliably interpret that small difference without reducing variation or collecting more evidence.
Use industrial camera image quality settings to establish the imaging baseline. Where frame metadata is available, verifying per-frame exposure and gain helps confirm that automatic controls are not changing the measurement.
Choose a textured ROI on the intended surface
The autofocus region of interest, or ROI, should contain useful texture at the depth you actually inspect. Exclude background labels, fixture edges, transparent covers, reflections, and features on other surfaces.
Start with a clearly identifiable feature, then enlarge the window enough to tolerate expected positioning variation. A tiny window can lose its target; a large window can reward the wrong depth.
Feature sampling matters too. As an illustrative starting requirement, suppose an inspection feature is 0.20 mm wide and you want it represented by 4 pixels across an 80 mm image width:
This is a sampling estimate, not a guarantee of autofocus performance. Lens contrast, illumination, feature orientation, and noise still affect the sharpness curve. The dimensional-inspection resolution guide explains why sampling requirements depend on the task.
An autofocus measurement window does not necessarily crop the camera's transmitted image. Host-side measurement may reduce processing work without reducing interface traffic. If bandwidth is also a concern, distinguish this from cropping the camera ROI at the source.
Keep the ROI fixed during the diagnostic sweep. If detection moves the window between frames, you are comparing different image content. The same feedback concern appears in exposure control driven by a detection ROI.
Record a finely sampled reference sweep
Use the documented safe focus range for the installed assembly. Do not infer actuator limits from an unrelated camera or lens.
At each sampled position, wait for settling, acquire an appropriate frame, and save the image, command, timestamp, and score. Repeat the sweep in the opposite direction. Direction-dependent differences can reveal mechanical backlash, actuator behavior, or inadequate settling.
One possible sharpness measure is mean squared image-gradient magnitude:
Use identical gradient filters and image scaling throughout the comparison. Noise can increase gradient energy, so a larger score is not automatically better focus. Whole-window intensity variance is another possible metric, but it also responds to changing scene contrast and is not a direct measure of edge sharpness.
Plot score against focus command. Then inspect images at every substantial peak, both boundaries, and several positions between peaks. Label which image actually supports the inspection.
A finite sweep identifies the best sampled position for that metric and ROI. It does not prove the exact continuous optimum, nor does it establish which physical surface you intended to inspect.
If the peak remains narrow compared with the sampling interval, repeat locally with smaller steps. If scores vary strongly at unchanged positions, return to the image baseline before interpreting the curve.
Set search limits before choosing a faster method
Several sharpness peaks usually mean that the ROI contains competing depths, or that the metric responds to more than the intended detail. Narrowing the search can help, but only after you identify the correct peak from saved images.
Consider this illustrative reference sweep. Focus commands below are arbitrary diagnostic units, not distance measurements or catalog specifications.
| Focus command | Sharpness score | Image interpretation |
|---|---|---|
| 20 | 45 | Both surfaces blurred |
| 30 | 82 | Background detail sharp |
| 40 | 57 | Between useful peaks |
| 50 | 64 | Inspection surface improving |
| 60 | 100 | Intended surface sharp |
| 70 | 61 | Inspection surface blurred again |
A search that stops after the first clear decline can settle near command 30. A coarse sweep sampling only commands 20, 40, and 60 happens to find the larger peak here. Shift a narrow peak between coarse samples, however, and the same method may miss it.
If valid part positions place the intended peak between commands 52 and 68, a tested search interval of 48–72 provides some margin. Validate that margin across the actual height range; it is not a universal allowance.
| Search approach | Appropriate use | Main limitation |
|---|---|---|
| Finely sampled sweep | Diagnostic reference and peak mapping | Many acquisitions and settling intervals |
| Coarse sweep followed by local refinement | Broad exploration with lower acquisition count | Narrow peaks can fall between coarse samples |
| Local hill climbing | Starting near a known, isolated peak | Can select a nearby secondary peak |
| Interval-reduction search | A stable interval with one dominant peak | Does not reliably resolve competing peaks |
Do not assume a control named hysteresis always means minimum focus step. Depending on the implementation, it may describe a score deadband, movement threshold, or termination criterion. Use the installed software's documented definition.
Budget the complete focus cycle
Search speed depends on more than sharpness calculation time. Count actuator motion, settling, exposure, readout, transfer, processing, and final positioning.
For a simple sequential implementation:
Here, t_frame covers acquisition and delivery of the required fresh image. Some systems overlap operations, so this estimate must be checked against measured timestamps.
Suppose a diagnostic sequence uses 8 ms for settling, 12 ms for a fresh frame, and 2 ms for scoring. Each sample takes approximately:
8 + 12 + 2 = 22 ms
A 31-position sweep therefore needs approximately 31 × 22 = 682 ms, before final positioning. A 10-sample search needs approximately 10 × 22 = 220 ms under the same assumptions.
Those are planning examples, not equipment performance claims. If the inspection allows only 250 ms, the shorter search leaves little allowance for retries or variable delivery time.
Measure command-to-final-image time rather than reporting only algorithm execution time. A focus routine that finishes quickly but returns an old image has not met the inspection deadline.
Verify repeatability against the reference
After choosing the ROI, range, and search strategy, test from near, middle, and far starting positions. Include the permitted part heights and representative surface finishes.
As an initial diagnostic exercise, run 30 repeats at each selected condition. This can expose common inconsistencies, but it does not establish a low production failure rate.
Record:
- Final focus command and score.
- Total elapsed time, including final settling.
- Whether the deadline was exceeded.
- Whether the inspection feature meets its own acceptance criterion.
- Whether a retry or range boundary was reached.
Compare the final image with the reference image for the intended surface, not merely with the largest score anywhere in the sweep. Useful acceptance criteria include edge transition width, code readability, or measurement repeatability, depending on the inspection.
Define a failure response. If the score is ambiguous, the peak lands on a boundary, or the deadline expires, reject or hold the inspection according to the machine's documented process. Do not silently treat the last available image as focused.
Where acquisition pauses or delayed delivery appear only under load, investigate camera acquisition stalls and recovery behavior separately from focus selection.
Know when autofocus is the wrong correction
Autofocus moves the plane of best focus. It cannot make widely separated surfaces equally sharp when the available depth of field is insufficient.
A smaller aperture can increase geometric depth of field, but it also reduces light and eventually increases diffraction blur. Evaluate the inspection image rather than assuming that stopping down always improves usable detail.
If part height is tightly controlled, fixed focus may provide better cycle-time predictability. If height changes among a few known positions, validated focus presets may be more appropriate than searching every cycle.
Motion blur also reduces sharpness without indicating the correct focus direction. Correct exposure and scene timing before allowing the focus loop to chase that blur. The moving-part exposure guide separates exposure duration from other acquisition timing.
Finally, focal length, back focus, and actuator command are different quantities. Review focal length versus back focus in board cameras if a replacement assembly cannot reach focus even with a stationary target.
Check the hardware before ordering
For board-level cameras, confirm the required acquisition controls and documented integration interface. The camera finder helps narrow the base camera choice, while the board-camera selection guide covers broader integration checks.
LS-BCM-0003 is a base-camera example, not a catalog-confirmed autofocus assembly. Its supplied catalog information does not establish a focus actuator or autofocus control interface.
- Sensor format
- 1/1.8"
- Lens mount
- C-mount
- Interface
- USB3
- Resolution
- 5 MP
For machine vision lenses, verify sensor coverage, mount compatibility, working distance, and the actual means of controlling focus. Use the lens finder to narrow optical candidates, not to infer an undocumented actuator.
LS-FFL-0602 is a lens candidate for optical compatibility checks. Its supplied catalog information does not establish automated focus control.
- Type
- Machine vision fixed
- Sensor format
- 1"
- Mount
- C-mount
- Resolution
- 6-10 MP
If processing moves to vision controllers, validate acquisition support and full-cycle timing on the intended configuration. Camera-port availability alone does not establish support for a particular focus assembly.
Before releasing the configuration, confirm:
- The measurement ROI stays on the intended surface throughout positioning variation.
- The reference sweep identifies the accepted inspection image.
- Search boundaries contain the valid peak with tested margin.
- Each evaluated frame follows the required settling interval.
- Repeatability and deadline criteria pass together.
- The camera, lens, actuator, and software interfaces are explicitly compatible.
Start the camera configuration workflow for a replacement imaging chain, or send your focus sweep, ROI images, height range, and cycle-time requirement through application support before selecting hardware.
Questions
Why does contrast autofocus select the background instead of the part?
The sharpness metric evaluates image content, not your intended inspection depth. A textured fixture or background can produce a stronger peak than the part. Place the measurement window on the inspection surface, inspect images across the focus range, and limit the search only after identifying the correct peak.
How small should the autofocus ROI be?
Use the smallest window that consistently contains useful detail despite expected part-position variation. Too little texture makes the score unstable, while excessive coverage can include competing depths. Test the window at the extremes of positioning and surface variation rather than choosing its size from processing speed alone.
Should every production inspection use a full focus sweep?
A finely sampled sweep is useful as a diagnostic reference, but it costs acquisition and settling time. After mapping the intended peak, compare faster strategies against that reference. A restricted, validated interval can reduce cycle time without requiring a full-range sweep for every inspection.
How can I separate autofocus hunting from unstable image quality?
Hold the focus command fixed and capture repeated images before changing search settings. Score variation at a stationary setting points toward image instability or noise. Direction-dependent focus positions suggest actuator behavior or settling problems, while different selected peaks suggest ROI or search-range ambiguity.
Do the camera and lens examples provide an autofocus system?
No such compatibility is established by the supplied catalog information. Automated focusing requires a supported actuator, control interface, compatible optics, and suitable acquisition timing. Confirm the complete assembly and software behavior before ordering; an imaging interface or lens mount alone does not establish autofocus capability.

