AI & Machine Vision

Machine Vision Engineering: From Photons to Decisions

A vision model can score well on a laptop and still fail on the line, in the vehicle or on the wall. This note walks the whole chain: optics and lighting, sensors and interfaces, embedded Linux camera bring-up, calibration, 3D, classical and learned algorithms, edge deployment and acceptance testing.

A camera product is a measurement system. Light leaves a source, interacts with a surface, passes through a lens, becomes charge on a sensor, crosses a bus, gets reshaped by an image signal processor and only then reaches an algorithm. Information lost early in that chain cannot be reliably recovered later. That is why we treat machine vision as a hardware, firmware and AI problem together.

This note describes an engineering method and failure modes common to vision systems. It is not a report on a named client, and it contains no client data or measured results. Numbers below are worked examples with stated assumptions. Always confirm part capabilities against current vendor documentation.

Start with the decision, then work backwards

Before choosing a camera, we write down what the system must decide and what a wrong decision costs. These answers drive nearly every later choice:

QuestionWhat it determines
What is the smallest feature or defect that matters?Object-space resolution, so sensor pixel count and field of view
How fast does the scene move?Exposure time, shutter type, light output, frame rate
How much can the distance to the object vary?Depth of field, aperture, focus strategy, lens type
How soon is the answer needed?Where inference runs, buffering depth, interface choice
Which error is worse: a miss or a false alarm?Operating threshold, review workflow, acceptance criteria
What changes over the product's life?Lighting control, recalibration, dataset refresh, model updates

Optics: the arithmetic that comes first

Suppose a part must be imaged across a 200 mm wide field of view from about 500 mm, using a sensor 2448 pixels wide with 3.45 µm pixels, and the smallest defect of interest is 0.3 mm.

sensor width      = 2448 px x 3.45 um           = 8.45 mm
object-space size = 200 mm / 2448 px            = 0.082 mm per pixel
pixels on defect  = 0.3 mm / 0.082 mm           = 3.7 px
magnification m   = 8.45 mm / 200 mm            = 0.0422
focal length f    = m x distance / (1 + m)      = about 20 mm   (thin-lens estimate)

About three to four pixels across the smallest feature is a common starting rule of thumb, not a guarantee: contrast, noise and lens sharpness decide whether it is enough. Since 20 mm falls between common fixed focal lengths, we would pick a stock lens and adjust the working distance, then confirm with a test chart and real samples.

Aperture is a trade. Stopping down increases depth of field, but costs light and eventually softens the image through diffraction. With the same setup at f/8, taking a two-pixel blur circle as acceptable:

depth of field    ~ 2 x N x c x (1 + m) / m^2
                  ~ 2 x 8 x 0.0069 mm x 1.042 / 0.0422^2   = about 65 mm
Airy disk (550 nm) ~ 2.44 x 0.55 um x 8                    = about 10.7 um (3 pixels)

The depth of field looks generous, but the diffraction spot is already about three pixels wide, which works against a small-defect requirement. A wider aperture with tighter part positioning may be the better design. We also check that the lens resolves the pixel pitch, covers the sensor format, and holds acceptable distortion and relative illumination into the corners. For dimensional measurement where distance varies, a telecentric lens removes most of the change in magnification, at a cost in size and price.

Lighting: the cheapest accuracy you will buy

Good lighting makes the feature of interest high-contrast and everything else boring. It usually does more for robustness than a larger model.

TechniqueGood forWatch out for
BacklightSilhouettes, dimensions, holes, presenceNo surface detail; needs access behind the part
Diffuse dome or flat domeCurved or shiny parts, printed marks on reflective surfacesSize and standoff; can wash out shallow texture
Low-angle dark fieldScratches, edges, embossing, engravingVery sensitive to height and orientation
CoaxialFlat specular surfacesLight loss in the beamsplitter; limited area
Polarized (with analyzer)Suppressing glare from non-metallic surfacesSignificant light loss; limited effect on bare metal glare
Narrow-band, NIR or UV with filterRejecting ambient light, material contrast, fluorescence, night operationSensor sensitivity at that wavelength; eye and skin safety assessment

Motion sets the exposure budget. In the example above, a part moving at 500 mm/s must be exposed for no more than about 160 µs to keep blur within one pixel (0.082 mm ÷ 500 mm/s). Exposures that short usually call for strobed LEDs, with the driver, trigger timing, duty cycle and thermal limits designed as part of the electronics.

Sensors and interfaces

  • Global versus rolling shutter. A global shutter exposes all rows together. A rolling shutter reads row by row, so fast motion skews shapes and pulsed light can band. Rolling shutter is fine for many static or slow scenes.
  • Monochrome versus color. Without a color filter array, a mono sensor collects more light and keeps finer detail. Use color only when color carries the decision.
  • Pixel size, noise and dynamic range. Compare sensors on measured quantum efficiency, read noise and full-well capacity (EMVA 1288 reports help), not megapixels. High-dynamic-range modes need checking for motion artifacts.
  • Data rate. 2448 × 2048 pixels at 8 bits and 60 frames per second is about 2.4 Gbit/s before protocol overhead. That already rules some links in and others out.
InterfaceTypical fitEngineering concerns
MIPI CSI-2Sensor close to an embedded SoCShort reach, lane count and rate, signal integrity, custom driver work
GMSL, FPD-LinkRemote cameras in vehicles and machines over coax or twisted pairSerializer and deserializer configuration, power over cable, link diagnostics
USB3 Vision / UVCCompact systems with a nearby hostCable length, host controller bandwidth, connector retention
GigE Vision (1 to 10+ GbE)Long cable runs, multi-camera cellsPacket loss, jumbo frames, NIC tuning, PTP time sync
CoaXPress, Camera LinkHigh-rate line-scan and area-scan inspectionFrame grabber cost, cabling, host throughput

For industrial cameras, the GenICam standard gives a common feature model across vendors and transports, which keeps application code less tied to one camera.

The vision pipeline

Eight stages, each with its own way to fail.

We instrument every stage so that a bad decision can be traced to the stage that caused it.

01

Illuminate

Controlled source, strobe timing, ambient rejection

02

Image

Lens, filter, focus and sensor exposure

03

Transport

Bus, DMA, buffers and timestamps

04

Condition

ISP or raw correction, cropping, scaling

05

Rectify

Calibration, undistortion, registration

06

Infer

Classical operators, neural networks or both

07

Decide

Thresholds, tracking, rules and actuation

08

Learn

Evidence capture, review, retraining, release

Camera bring-up on embedded Linux

On a custom board, getting a first good frame spans the schematic (rails, power sequencing, reference clock, reset, I²C), the device tree, the sensor driver and the SoC's capture pipeline. Linux exposes this through V4L2 and the media controller framework, with libcamera or a vendor camera stack above it and GStreamer commonly used to move frames between hardware blocks. Platforms such as NVIDIA Jetson, Qualcomm and NXP i.MX each differ in ISP access and tooling, and that difference should influence SoC selection.

# What did the kernel find, and how is the pipeline wired?
v4l2-ctl --list-devices
media-ctl -d /dev/media0 -p

# Supported formats and controls on the capture node
v4l2-ctl -d /dev/video0 --list-formats-ext
v4l2-ctl -d /dev/video0 --list-ctrls

# Can it stream steadily, before any application code is involved?
v4l2-ctl -d /dev/video0 --stream-mmap --stream-count=600 --stream-to=/dev/null

The image signal processor deserves its own plan. Black level, lens shading, white balance, demosaic, noise reduction, sharpening and tone mapping make pictures pleasant to people, but can erase fine texture or shift behavior between scenes. For measurement and inspection we lock exposure, gain and white balance where possible, and version the ISP tuning with the model, because a tuning change is an input-distribution change.

Calibration and geometry

Any system that measures, guides a robot or fuses cameras needs a geometric model. Intrinsic calibration (focal length, principal point, distortion) is commonly done with planar targets using Zhang's method, as implemented in OpenCV. Extrinsic and hand-eye calibration then relate cameras to each other, to the machine or to a robot.

# obj_points: board corner coordinates per view (mm)
# img_points: matching sub-pixel detections per view
rms, K, dist, rvecs, tvecs = cv2.calibrateCamera(
    obj_points, img_points, image_size, None, None)

# A low RMS reprojection error is necessary, not sufficient:
# verify on held-out views and against a known physical length.
  • Cover the whole image, including corners, and tilt the target through a range of angles.
  • Lock focus and aperture mechanically before calibrating; changing either invalidates the result.
  • Test calibration stability over temperature, vibration and transport.
  • Give fielded units a quick health check against a fixed reference, so drift is detected before it affects decisions.

When 2D is not enough: 3D sensing

MethodStrengthsLimits
Passive stereoLow cost, works outdoors, no emitter neededStruggles on textureless or repetitive surfaces
Structured lightDense, fine depth at short rangeAmbient light, reflective surfaces, motion during pattern sequences
Time of flightCompact, direct depth at video rateMultipath, interference, lower lateral resolution
Laser triangulationPrecise height profiles on moving partsNeeds motion or scanning; occlusion and speckle; laser safety

For stereo, depth uncertainty grows with the square of distance: ΔZ ≈ Z² · Δd / (f · B), where f is focal length in pixels, B the baseline and Δd the disparity error. Doubling the range roughly quadruples the depth error, so baseline and lens are chosen from the farthest distance that must still meet tolerance.

Algorithms: classical, learned or hybrid

ApproachUse it whenMain risk
Classical (thresholding, morphology, edge fitting, template matching, code reading)Geometry and lighting are controlled and the rule can be stated; measurements must be explainableBrittle when appearance varies
ClassificationOne verdict per image or regionLearning background cues instead of the defect
Detection and segmentationLocation, count, size or shape matterLabeling effort and label consistency
Anomaly detectionGood samples are plentiful, defects are rare or unpredictableFlags harmless variation; needs careful thresholds
HybridClassical steps locate and normalize, a network judges the hard partMore stages to version and test

Data is the specification

  • Collect from the real optical setup. Images from a phone or a different lens teach the wrong distribution.
  • Write a labeling standard with boundary examples, and measure disagreement between labelers. A model cannot be more consistent than its ground truth.
  • Split by lot, date, unit or site, not by random frame. Near-identical frames in train and test produce scores that will not survive deployment.
  • Cover the nuisance conditions: shifts, suppliers, dirt on the window, aging LEDs, temperature, weather.
  • Use augmentation and synthetic data to widen coverage, and always report results on real held-out data.

Deploying at the edge

The target may be a microcontroller, an application processor with an NPU, a GPU module or an FPGA. We choose from the latency, power, thermal, cost and supply-life budget, then confirm on hardware, because operator support differs between toolchains such as TensorRT, LiteRT (TensorFlow Lite) and ONNX Runtime. See NPU versus MCU for on-device AI and on-device versus cloud AI.

  • Budget latency end to end: exposure, readout, transfer, preprocessing, inference, postprocessing and actuation. Report tail latency, not only the average.
  • Avoid unnecessary copies. Pass hardware buffers between capture, scaler and accelerator; pre- and postprocessing on the CPU often dominate.
  • Quantize with evidence. Re-evaluate every critical class after conversion, not just the aggregate score. Our note on edge AI quantization goes further.
  • Test thermally in the enclosure. Throttling after a long soak changes latency, and a hotter sensor is a noisier one.
  • Define overload behavior: which frames are dropped, how it is logged and what the safe output is.

Proving it works

"99% accurate" says little when defects are rare: a system that passes everything can score that high. We agree on measures tied to cost, with sample sizes large enough to support them.

MeasureQuestion it answers
Escape (miss) rate per defect classHow often does a real problem get through?
False reject or false alert rateHow much good product or operator attention is wasted?
Precision-recall at the chosen thresholdWhat is the trade at the operating point actually shipped?
Repeatability and reproducibilityDoes the same part get the same answer across runs, units and operators?
Latency distribution and dropped framesDoes the answer arrive in time, every time?
Performance by conditionWhich lighting, lot, site or temperature is the weak one?

Common field failures

SymptomLikely causesHow we investigate
Accuracy drifts over weeksLED aging, dirty window, focus creep, new material or supplierTrend brightness, sharpness and score distributions against a reference target
Intermittent corrupted or missing framesSignal integrity, power noise, buffer starvation, network packet lossCheck driver error counters and sequence numbers; probe the link; stress CPU and memory
Horizontal bandingRolling shutter against pulsed or mains-driven lightMatch exposure to the flicker period, use constant-current drive or synchronize the strobe
Measurements shift with temperatureLens and mount expansion, calibration changeThermal chamber sweep with a fixed target; revise mechanics or compensate
Good on the bench, poor on siteAmbient light, vibration, viewpoint, unseen backgroundsCapture raw failing frames with metadata and replay them through the pipeline
Multi-camera results disagreeUnsynchronized exposure, timestamp error, extrinsic driftHardware trigger or PTP, then re-verify extrinsics

Operations, security and privacy

Ship the means to improve the system: store a sampled and event-triggered set of images with exposure, model, ISP and calibration versions; send uncertain cases to human review; and release models through staged, reversible updates. Fleet retraining and OTA updates cover the mechanics. Where people may appear in frame, decide early what is processed on-device, what leaves it, how long it is kept and who can see it, with secure boot and signed model artifacts protecting the device itself.

An illustrative walkthrough

This is a composite showing how such an engagement can run, not a report on one named client.

  • Feasibility: image good and defective samples under several lighting geometries before committing to hardware or a model.
  • Specification: fix resolution, exposure, latency and per-class acceptance criteria with the people who own the cost of errors.
  • Prototype: an off-the-shelf camera and compute module, a classical baseline, then a learned model where the baseline falls short.
  • Productize: custom electronics and optics mounting if volume or size justifies it; driver, ISP tuning and calibration station.
  • Validate: blind test on later lots, environmental and soak testing, shadow-mode running beside the existing process.
  • Operate: monitoring, review queue, retraining criteria and rollback.

For a related product shape, see our driver behavior edge AI dash unit, which runs computer vision on-device and uploads events rather than continuous video.

What you receive

The deliverables of a machine vision engagement.

Scoped to your product; we can take one layer or the whole chain from lens to cloud.

Feasibility report

Sample images, optical calculations, lighting trials and a clear statement of risks.

Imaging design

Sensor, lens, lighting, interface and compute selection with the reasoning behind each.

Camera software

Drivers, capture pipeline and ISP configuration building reproducibly from your repository.

Models and datasets

Versioned data, labeling standard, training code and an evaluation report by class and condition.

Calibration and test tools

Production calibration procedure, health checks and a replayable regression set.

Runbook and handover

How to monitor, diagnose, update and roll back the system in the field.

Common questions

Can you work with the camera we already have?

Often, yes. We first check whether its images contain the information the decision needs. If they do not, we show why and what change in optics, lighting or sensor would fix it.

How many images are needed to train a model?

It depends on how varied the good and defective appearances are, and on how confident the acceptance result must be. A feasibility study on real samples gives a better answer than a fixed number.

Should inference run on the device or in the cloud?

Run on the device when latency, bandwidth, privacy or offline operation matter. The cloud suits fleet analytics, review, retraining and workloads that can wait. Many products use both.

Do you need deep learning for machine vision?

Not always. Controlled measurement and code-reading tasks are often better served by classical methods. Learned models earn their place where appearance varies in ways rules cannot capture.

Let's build

Tell us what your system needs to see — get a scoped plan back in days, not weeks.