Some original image labels are retained; figure captions and explanations are provided in English.

PART V · DEEP LEARNING

How Does OCR Work? Reading Serial Numbers, Barcodes, and Data Matrix Codes

Text detection and recognition are separated before comparing classical OCR, CRNN/CTC and Transformer approaches. A laser-marked metal-part example follows the chain from imaging conditions to format and check-digit validation. Barcode and Data Matrix reading, character-level versus exact-string accuracy and traceability for unreadable products complete the inspection workflow.

Article sectionsWhat is OCR, and how is it used in industry?Why separate text detection from text recognition?Classical OCR versus deep learning-based OCRThe CRNN and CTC approachHow does Transformer-based OCR differ?Where do Tesseract and PaddleOCR fit in?Why are characters marked on metal difficult to read?Are barcode and Data Matrix reading the same as OCR?In what order should image preprocessing be applied?Confidence and character-level error analysisCheck digits, formats, and business rulesMES and traceability integrationExample: reading a serial number on a laser-marked metal partWhen is an alternative to OCR needed?Character detail at the pixel level in OCR imagesDifferent defects in printing, dot peening, and laser markingHow should an OCR dataset be designed?Interpreting CER, WER, and exact string accuracy togetherError handling: what should happen to an unreadable product?The distinction between optical verification and text validationFrequently asked questionsImage sources

Text detection, character recognition, DPM, and barcode reading; quality control, traceability, and error tolerances. This guide examines the assumptions behind the method, the conditions under which it can be used, its failure modes, and the decisions that need to be made in the field.

What is OCR, and how is it used in industry?

Short answer: Optical Character Recognition (OCR) is a collection of methods for converting written characters in an image into machine-processable text. Industrial systems use it to read serial numbers, production dates, batch codes, meter readings, labels, and characters laser-marked onto metal surfaces. However, OCR does not mean reading every type of visual code: barcodes and Data Matrix codes rely on decoding principles that differ from character recognition.

Finding a product label in a camera image does not mean that the correct product has been read. The recognized string must be matched against the production recipe, its check digit verified if one exists, and the result transferred to the traceability system without errors. OCR is only the visual perception layer; product identification is an end-to-end data validation problem.

OCR workflowLocating and recognizing text are separate stagesimagelocaterecognizevalidateConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Locating and recognizing text are separate stages

Why separate text detection from text recognition?

Text detection finds where text is located in an image. Text recognition predicts the character sequence within the detected region. These two stages can be combined within a single network, but they solve logically distinct problems. If a camera image contains several labels in different locations, the correct text region must first be selected. Reading the wrong label perfectly is still an error for the overall system.

A text detection model may produce outputs such as rotated quadrilaterals or polygons, enabling perspective correction. If the text region is too small or affected by excessive glare, the recognition model lacks sufficient pixel information. Optics, alignment, and character recognition should therefore not be treated as disconnected optimization steps in an OCR workflow.

Text regionDealing with rotation, perspective, and excessive glareskewrectifycroprecognizeConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Dealing with rotation, perspective, and excessive glare

Classical OCR versus deep learning-based OCR

Classical OCR systems may use character thresholding, connected-component analysis, template matching, and features tailored to specific fonts. Deep learning-based methods may instead use CNN, recurrent network, or Transformer components for feature extraction and character sequence decoding. Which family is appropriate depends on the diversity of character shapes, image quality, and the device's processing speed.

A simple approach can be highly stable on lines with a fixed font, a fixed template, and controlled lighting. More advanced text detection and recognition systems may be useful when text appears in variable locations, different languages, or complex backgrounds. However, if the text format is fixed, applying format checks is generally safer than accepting every possible character produced by the model.

Real scanned page with uneven background illumination.
Real photograph / transformation: Real scanned page with uneven background illumination.

The CRNN and CTC approach

In OCR architectures such as the Convolutional Recurrent Neural Network (CRNN), a sequence of features extracted from the image is used to predict characters across time or spatial positions. Connectionist Temporal Classification (CTC) is a loss and decoding approach that enables learning from sequences without requiring precise character alignment for every sample. This is particularly useful for training data that does not explicitly mark where each character begins along a line.

When interpreting CTC output, attention must be paid to how repeated characters, blank symbols, and character order are decoded. Accidentally collapsing repeated digits such as "11" into a single digit, or confusing similar-looking characters such as 0/O, 1/I, 5/S can cause serious data errors in industrial identification. Character matching and field-format validation can catch some of these errors, but they cannot compensate for information missing from the captured image.

How does Transformer-based OCR differ?

Transformer-based recognition methods can use attention to model relationships between visual features and characters. Text line length, character diversity, and context can affect the model's output. Some architectures use autoregressive decoding, while others use parallel prediction or CTC-like objectives. The claim that "Transformer OCR is better" is meaningless without specifying the task and data.

For random strings such as serial numbers, autocorrection based on natural language knowledge is particularly risky. A language model replacing A0B8 with a more common-looking sequence can create an incorrect product record. A genuine serial number appearing statistically "implausible" does not mean it is wrong. Characters read from identification fields should be validated against business rules; linguistic prediction must not replace data validation.

Where do Tesseract and PaddleOCR fit in?

Tesseract is a mature, open-source OCR engine. PaddleOCR is a current open-source ecosystem offering text detection, recognition, and document processing components. Choosing between them requires considering pretrained model versions, language support, licensing, the target operating system, character format, and latency requirements. Demos on product pages are no guarantee of performance in actual metal surface inspection.

In most applications, producing the right image also comes before choosing the right OCR engine. On a surface with a low-contrast laser mark, a different lighting angle, polarization, or illumination that reveals surface relief may offer a much greater improvement than changing the model. Model architecture alone cannot work miracles on an image that lacks sufficient photometric information.

Why are characters marked on metal difficult to read?

Direct Part Marking (DPM) covers codes and marks formed directly on metal or plastic surfaces. Marks produced by laser processing, dot peening, embossing, or chemical marking behave differently in images from black ink on paper. Specular reflection, surface tilt, oxidation, and machining marks on shiny metal can alter character contrast.

On a metal surface, the inner opening in the digit 8 may be obscured by a reflection; the letter B may appear similarly distorted. In this situation, simply increasing the OCR model's size will not provide a lasting fix for misclassification. Improving character-to-background separation through suitable lighting geometry and optical filters is a better first step.

DPM and printingEmbossed or laser-marked features on metal are challengingsurfacelightingcodereadConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Embossed or laser-marked features on metal are challenging

Are barcode and Data Matrix reading the same as OCR?

No. A barcode or 2D Data Matrix code contains a standardized arrangement of visual symbols and is read using dedicated decoding algorithms. A human-readable serial number, by contrast, is a character recognition problem. Printing both a Data Matrix code and text on the same product is common; cross-checking the two sources can reduce errors. However, if the same incorrect serial number is printed in both the code and the text, both readings may return the same wrong result.

A Data Matrix code can carry a substantial amount of data in a small area and includes error correction mechanisms. Nevertheless, a code may remain unreadable if it is damaged, excessively reflective, insufficiently resolved, or severely distorted by perspective. Code readability should be evaluated together with the optical setup and the quality of production marking.

Code validationA check digit or data format can helpdecodesyntaxchecksumtraceConceptual technical diagram · Not an architectural drawing to scale
Original diagram: A check digit or data format can help

In what order should image preprocessing be applied?

Preprocessing is useful insofar as it makes the problem easier. ROI cropping, geometric correction, contrast adjustment, illumination normalization, and noise reduction may be applied. However, aggressive thresholding can erase thin strokes; excessive sharpening can create artificial edges; and JPEG compression can produce blocking and ringing artifacts around characters. Every operation should be evaluated against actual reading performance.

For example, global thresholding may cause some letters to disappear from a scanned page with uneven background illumination. Local thresholding can help, but it cannot be claimed to outperform other approaches on every image. On a DPM surface, characters reflecting light in different directions can also complicate local normalization.

Binary image of the real page using Otsu's method.
Real photograph / transformation: Binary image of the real page using Otsu's method.

Confidence and character-level error analysis

OCR performance is not evaluated solely by asking whether the text is correct. Character Error Rate (CER) is calculated by normalizing character insertion, deletion, and substitution errors by the length of the reference text. Word Error Rate (WER) operates at the word level. Exact-match rate is particularly important for short fields such as serial numbers, where a single character error can invalidate the entire product identity.

For example, one error in a 12-character serial number corresponds to a character error rate of approximately 8.3%. In terms of product identity, however, the entire string is wrong. A metric such as "99.5% character accuracy" therefore does not, on its own, explain the cost of recording an incorrect serial number. Final field validation and, where possible, rereading by the machine are important.

Check digits, formats, and business rules

If a serial number contains a specific prefix, a fixed length, or a date field, validation rules can catch misreadings. Some systems also use formally defined check-digit algorithms. However, it should not be assumed that a check digit can automatically be applied to every serial number. The organization's data format must be known, and validation rules must match the source system.

0 and O can be confused in a product code; this ambiguity can be narrowed if the expected field contains digits only. However, arbitrary conversions create other errors if the product code contains both letters and numbers. Automatic corrections should be logged, and it should be possible to compare the raw OCR output with the validated output when needed.

Confidence and the operatorRereading low-confidence resultsscoreretryhumanauditConceptual technical diagram · Not an architectural drawing to scale
Original diagram: Rereading low-confidence results

MES and traceability integration

The OCR result must be matched to the correct product. If the camera captures a frame containing two products, the system must determine which serial number belongs to which physical part. Conveyor synchronization, triggering, part identity, and the order of database writes all matter. Matching a correct code to the wrong product can be a system error that is harder to detect than a misrecognized character.

If a reading fails, dangerous defaults such as "accept an empty string" or "reuse the last successfully read code" must be avoided. The response to an error, whether retriggering, operator intervention, or a safe rejection decision, must be explicitly defined. Even the loss of a single row of traceability data can affect a subsequent product recall.

Example: reading a serial number on a laser-marked metal part

Suppose each part carries a 14-character serial number. The field of view and lighting are fixed, the character region is located using a mechanical reference, and perspective and reflections are checked in the image. The OCR engine predicts the character sequence; field-format and uniqueness checks validate the result. Finally, the result is matched to the product's tracking record. Low-confidence or inconsistent results are sent for image recapture or operator inspection.

OCR accuracy is not the only success criterion. Acceptance of incorrect serial numbers, the unreadable-part rate, recapture time, duplicate records, database latency, and operator intervention are measured together. Production trials test how the system behaves when the camera window becomes dirty or marking depth changes.

Application architectureThe serial number is matched against the MEScameraOCRMESverificationConceptual technical diagram · Not an architectural drawing to scale
Original diagram: The serial number is matched against the MES

When is an alternative to OCR needed?

If the text information already exists in the PLC or MES, trying to obtain it again through OCR may be unnecessary. If the real aim is to verify the match between a physical part and its system record, a 2D code, RFID, or another identification approach may be considered. However, OCR may still be useful if evidence is required that the relevant mark has been correctly applied to the physical surface.

If very small, low-contrast marks cannot be read reliably from a single photograph, multiple lighting setups, a second exposure, or a different wavelength may be needed. Before concluding that "OCR is not possible," the effect of optical conditions on data readability should be examined.

Character detail at the pixel level in OCR images

Character height and stroke thickness limit which recognition methods can succeed. For example, if we aggressively downsample a serial number that is 12 pixels high, the two openings in the digit 8 or the internal structure of the letter B may disappear. This kind of information loss cannot automatically be recovered with a larger recognition model. Preserving character height on the sensor starts with lens and field-of-view selection.

Character height alone is not a sufficient criterion; focus, motion blur, compression, lighting, and surface tilt also matter. If a laser mark on a moving conveyor shifts by several pixels during the exposure, character strokes can merge. Reducing exposure time decreases blur but may also reduce the number of photons in the image. Strobe illumination or stronger lighting with suitable geometry can change this trade-off.

When an OCR engine fails, the first question is often "Which architecture should we use?" Yet if a person can easily read a new image of the same part taken with closer-view optics and better lighting, this may indicate that image acquisition is the underlying problem. The model's role is not to create stroke detail that was never captured by the sensor.

Different defects in printing, dot peening, and laser marking

For ink-printed labels, fading, smearing, color contrast, and paper wrinkles are prominent issues. For dot-peened characters, the arrangement of dot patterns and the surface's angle-dependent reflection matter. In laser marking, surface oxidation, microtexture, and burn marks affect character appearance. The same OCR model should not be expected to perform equally well across all these domains without training.

In industrial identification, readability is not just a matter of software accuracy; it is also a quality output of the marking process. An incompletely marked character may look like an OCR error but is actually a production defect. In such cases, the system should not stop at predicting the correct string; it can also inspect print quality separately. Character completeness, module distortion, and surface contrast, for example, can be checked independently.

At a facility receiving products from different suppliers or marking devices, the optics and training data should cover this diversity. Examples of the same character family produced by several different marking methods can be used. Leaving defective marks entirely to autocorrection creates hidden data corruption in traceability records.

How should an OCR dataset be designed?

Collecting different character combinations alone is not enough. Camera angle, material, marking depth, contamination of the protective window, product batch, and background illumination should also be represented. If many images belong to the same physical part, randomly distributing them between training and test sets can inflate test performance. Group-based splitting by attributes such as part identity and production day may be necessary.

For annotation, the correct text region and character sequence are stored for each image. Treating the serial number in the source system as the image's ground truth is not always safe; the product may have been marked incorrectly. A discrepancy between these two sources may be a genuine production mismatch rather than an OCR model error. Such examples should be flagged as separate cases.

There should also be explicit states for ambiguous and unreadable characters. Forcing a definite character label onto text that an operator struggles to read causes the model to learn incorrect information. An "unreadable" label and an image recapture procedure are part of a good dataset.

Interpreting CER, WER, and exact string accuracy together

Character error rate expresses substitution, deletion, and insertion errors relative to the total reference character count. Word error rate is meaningful for longer passages of prose. For a serial number, however, an incorrect overall string means an incorrect production record, so exact match may be a much more direct business metric. The same OCR model should be evaluated with different definitions of success in different applications.

For example, a single incorrect character in a 20-character field gives a CER of 5%. But if that character causes one product to be confused with another, the impact is substantial. By contrast, a single character error in a long descriptive text may not affect operations. In critical fields, character-level error analysis and product-level matching errors should be reported together.

It should also be remembered that character confidence scores are not sufficient on their own. A model can confuse O and 0 with high confidence. Using the field format and check digit, and where possible comparing against a Data Matrix code or a second reading source, may be more reliable.

Error handling: what should happen to an unreadable product?

An OCR system must not automatically assign the last successfully read serial number to an unreadable part. This kind of "last value remains valid" behavior can cause silent traceability errors on high-speed lines. Every image must be associated with a product trigger ID and timestamp. A failed reading must be recorded under its own identity.

The workflow can define options for recapture attempts, a second image under different lighting, and manual verification. However, the product must physically remain within the camera's inspection region for a new image to be taken. If the product sorting mechanism is far away, the latency budget must be calculated to include this second operation.

Operator intervention also needs to be logged. A manually corrected serial number can be stored in a way that identifies who made the correction and on what evidence. This is not just software discipline; it is a requirement of production traceability.

The distinction between optical verification and text validation

The OCR output may have the correct format even when the physical marking is poor. For example, even if a model correctly infers a worn digit 8 from context, the mark's visual quality may still be below the required standard. In this case, the identity is correct but the marking quality is defective. Combining two different business problems under a single "OCR success" label is inappropriate.

Some projects aim only to obtain the serial number, while others aim to verify the readability of the mark itself. The latter requires measurements such as character size, contrast, stroke completeness, and symbol quality. The vision system's acceptance criteria should explicitly state which of these objectives is being targeted.

A good field trial should use versions of the same string marked at different levels of physical quality. This reveals whether excessive "autocorrection" allows the model to pass poor-quality marking without detecting the production issue.

Advanced engineering details to consider in the field

Different error layers in text reading

Errors in an OCR system do not occur only in the character recognizer. Failure to locate the text region, incorrect cropping of the right region, merged characters, reduced contrast, or misinterpretation of the permitted string format can all lead to the same outcome. For example, when '8' and 'B' are confused, the model's class output should be examined; but if the text region was incompletely cropped from the start, changing the character model is not the solution. Error analysis should separately measure the performance of region detection, image preparation, character recognition, and rule validation. This distinction reduces maintenance costs.

Serial number validation

It is not enough for all the characters read on a production line to be visually correct. Serial number length, the allowed alphabet, a check digit, or consistency with the production order can provide additional validation. However, these rules do not magically correct OCR errors. If there are several possible readings, selecting the one that satisfies the rules can hide a genuine product error that violates them. It is therefore useful to retain raw OCR output, alternative character scores, and rule results in a traceable form. A transparent error policy should be preferred to silent autocorrection in a traceability system.

DPM and print quality

Laser-marked or dot-peened Data Matrix codes may not look as flat and high-contrast as printed labels. On metal surfaces, the angle of incident light and the depth of the mark determine the visibility of the code's cells. Suitable illumination often provides more benefit than a larger OCR model. Standards-based code evaluation is not simply a "read/unreadable" decision; print or marking quality also has its own criteria. In particular, the standard and measurement conditions used for quality assessment must be specified. Changing camera settings may affect both reading performance and the quality score.

Reading time and the production cycle

Failure to read a serial number may require the system to acquire another image while keeping track of the product's position on the belt. However, not every line offers a second triggering opportunity. The first-pass read rate, character error rate, and routing of unreadable products must therefore be designed together. Model inference time alone does not constitute the cycle time; exposure, transfer, cropping, validation, database queries, and the PLC response all belong to the complete chain. Assigning recognized characters to the wrong product can create a more serious traceability problem than a single character error.

Application scenario: the production cost of Data Matrix reading

If serial numbers are applied to two parts per second and the unreadable rate is 1%, approximately seventy-two reprocessing or manual inspection operations may be needed per hour. These rates are only an illustrative calculation. Marking quality, lighting geometry, exposure, opportunities for image recapture, and database validation must be considered together. A third-party OCR service returning the correct text does not, by itself, prove that the text was marked on the correct part.

Field test checklist

  • Has it been documented which tests are kept independent by product, shift, and imaging conditions?
  • Has a distinction been made between failures that can be corrected through the algorithm alone and those requiring optical or process changes?
  • Has it been verified that the model score does not replace the physical acceptance criterion?
  • Are the input resolution, model version, threshold, and operating hardware held constant in the experiment records?
  • Are illustrative visuals clearly distinguished from actual measured model results?
  • Have false rejections, missed defects, latency, and the reinspection workload been reported separately?

Frequently asked questions

What is the difference between OCR and Data Matrix reading?

OCR recognizes written characters. A Data Matrix reader decodes data from a standardized module pattern. The two outputs can be cross-checked.

Is an OCR model's confidence score directly equivalent to its accuracy?

No. Confidence scores can be misleading when the data distribution changes. Format checks, rereading, and calibration where necessary are required.

Which metric matters more: CER or exact match?

Exact match is crucial in fields such as serial numbers, where one character error invalidates the entire identity. CER helps investigate the types of errors.

What lighting is suitable for laser-marked characters?

It depends on the surface, marking type, and reflection direction. Side or coaxial illumination can be tested; no single lighting type is superior for every metal surface.

Should OCR output be corrected automatically?

Only when there is an explicit data format and a validated business rule. A language model converting random serial numbers into "plausible" characters can create incorrect records.

References and image provenance

Technical references and original publications are listed below. The photographs used in the visual examples come from real CC0/public-domain samples; transformations made for comparison are explained. The diagrams are original designs. Illustrative examples are not presented as trained-model performance.

  1. https://github.com/tesseract-ocr/tesseract
  2. https://github.com/PaddlePaddle/PaddleOCR
  3. https://www.gs1.org/standards/barcodes/2d
  4. scikit-image example data: source photographs and reuse notes

Image sources and illustration note

The photographic examples come from the scikit-image sample data collection. Added boxes, masks, synthetic defects, and heatmaps are illustrations explaining concepts; they are not outputs of a trained model or validated performance results. The technical diagrams are original drawings included in the package.

Source and usage notes for the sample images