Barcode Reading Tutorial
Introduction
This tutorial describes how to use Zivid SDK to detect and decode barcodes in a 2D image.
Prerequisites
A valid software license. Contact us to get your license.
Types of Supported Barcodes
Barcodes are a visual, machine-readable representation of data, typically in a pattern of parallel lines, spaces or shapes that encode information such as product numbers. Zivid SDK supports the following linear (1D) and matrix (2D) barcode formats:
Linear: EAN-13, EAN-8, Code 128, Code 93, Code 39, UPC-A [1], UPC-E, ITF
Matrix: QR Code, Data Matrix
Examples of supported barcode formats.
Barcodes may come in various sizes, where the width of the smallest bar or space is the main sizing parameter. This smallest feature is called the module size (or X-dimension), and it is commonly expressed in mils, where one mil is 1/1000 inch (0.0254 mm). For example, standard retail linear barcodes typically vary between 7 mil (0.178 mm) and 13 mil (0.330 mm). Smaller barcodes require higher resolution to be detected and decoded reliably.
Examples of different Code 128 barcode sizes captured from the same distance.
Barcode Reading API
Linear barcodes are detected and decoded in two steps. Detection identifies candidate regions in the image that are likely to contain a barcode. Since decoding has not yet been attempted, the list may include false positives: regions that resemble a barcode but may not actually be one.
Alternatively, both linear and matrix barcodes can be detected and decoded in a single function call: see Reading.
Start by initializing the barcode detector. Note that this should only be done once and not for every capture.
Then specify which of the supported barcode formats to detect, rather than looking for all formats. This will speed up detection and make decoding more robust. In this example we generalize and select all supported formats for demonstration purposes.
// Select your specific barcode formats for optimal performance
const auto linearFormatFilter = LinearBarcodeFormat::code128 | LinearBarcodeFormat::code93
| LinearBarcodeFormat::code39 | LinearBarcodeFormat::ean13
| LinearBarcodeFormat::ean8 | LinearBarcodeFormat::upcA
| LinearBarcodeFormat::upcE | LinearBarcodeFormat::itf;
const auto matrixFormatFilter = MatrixBarcodeFormat::qrcode | MatrixBarcodeFormat::dataMatrix;
# Select your specific barcode formats for optimal performance
linear_format_filter = {
LinearBarcodeFormat.code128,
LinearBarcodeFormat.code93,
LinearBarcodeFormat.code39,
LinearBarcodeFormat.ean13,
LinearBarcodeFormat.ean8,
LinearBarcodeFormat.upcA,
LinearBarcodeFormat.upcE,
LinearBarcodeFormat.itf,
}
matrix_format_filter = {MatrixBarcodeFormat.qrcode, MatrixBarcodeFormat.dataMatrix}
Successfully detecting and decoding barcodes depends heavily on a sharp and well-exposed 2D image. Use the suggested 2D settings from the barcode detector and capture a 2D frame.
Detecting
Detect linear barcode candidate regions:
Each detection candidate only exposes a bounding box, since it has not been decoded yet.
The bounding box is a BoundingBox: the x and y fields give the top-left corner, and width and height give its size, all in pixels.
if(!detectionResults.empty())
{
std::cout << "Detected " << detectionResults.size() << " linear barcode candidates:" << std::endl;
for(size_t i = 0; i < detectionResults.size(); ++i)
{
std::cout << "-- Candidate " << (i + 1) << ":" << std::endl;
std::cout << " Bounding box: " << detectionResults[i].boundingBox() << std::endl;
}
}
else
{
std::cout << "No linear barcode candidates detected" << std::endl;
}
Decoding
Decoding reads the actual code from each candidate produced by detection, which is also what filters out the false positives. If a candidate could not be decoded, the corresponding result is empty.
Detecting and decoding in two separate steps gives you explicit access to candidate regions and their bounding boxes before decoding.
Decode the detected candidates:
Each decoded result exposes the code, format, its own bounding box, and its orientation.
Orientation is a VectorXY: a unit vector in image pixel coordinates.
For a linear barcode, it points in the code’s read direction, from its first bar to its last.
Zero degrees points along the positive x-axis, and the angle increases clockwise as the image is displayed.
Call VectorXY::angleInDegrees or VectorXY::angleInRadians to get the orientation as an angle in degrees or radians.
The bounding box does not follow the orientation: it is always a rectangle aligned with the image axes that encloses the code.
Arrows show each barcode’s read direction. 0 degrees points right, and angles increase clockwise.
Print the decoded results:
if(decodingResult.has_value())
{
const auto &decoded = decodingResult.value();
std::cout << " Code: " << decoded.code() << std::endl;
std::cout << " Format: " << toString(decoded.codeFormat()) << std::endl;
std::cout << " Bounding box: " << decoded.boundingBox() << std::endl;
std::cout << " Orientation: " << decoded.orientation() << " ("
<< decoded.orientation().angleInDegrees() << " degrees)" << std::endl;
}
else
{
std::cout << " Failed to decode" << std::endl;
}
Reading
To detect and decode in one call, use Experimental::Toolbox::BarcodeDetector::readLinearCodes.
It returns only the decoded results, without the intermediate candidates.
Use this whenever you only need the final decoded barcodes.
Matrix barcodes only ever have this one-call reading API, with no separate two-phase detect/decode split.
Experimental::Toolbox::BarcodeDetector::readMatrixCodes is both the detection and the decoding step in one:
For the corresponding API, see Barcode Detection.
For a matrix barcode, the orientation points from the symbol’s left edge to its right edge, as seen with the symbol upright. An upright matrix barcode is therefore at zero degrees, and the angle increases clockwise as the image is displayed.
Print the decoded matrix barcodes with their bounding boxes and orientations:
if(!matrixBarcodeResults.empty())
{
std::cout << "Detected " << matrixBarcodeResults.size() << " matrix barcodes:" << std::endl;
for(const auto &result : matrixBarcodeResults)
{
std::cout << "-- Code: " << result.code() << std::endl;
std::cout << " Format: " << toString(result.codeFormat()) << std::endl;
std::cout << " Bounding box: " << result.boundingBox() << std::endl;
std::cout << " Orientation: " << result.orientation() << " ("
<< result.orientation().angleInDegrees() << " degrees)" << std::endl;
}
}
else
{
std::cout << "No matrix barcodes detected" << std::endl;
}
if matrix_barcode_results:
print(f"Detected {len(matrix_barcode_results)} matrix barcodes:")
for result in matrix_barcode_results:
print(f"-- Code: {result.code()}")
print(f" Format: {result.code_format()}")
print(f" Bounding box: {result.bounding_box()}")
print(f" Orientation: {result.orientation()} ({result.orientation().angle_in_degrees():.1f} degrees)")
else:
print("No matrix barcodes detected")
Check out the LiveBarcodeReader (C++) or live_barcode_reader (Python) sample to see this used in a continuously running live view. It draws each result’s bounding box, code, and orientation arrow as barcodes move through the frame:
const auto frame2d = camera.capture2D(settings2d);
const auto sourceImage = frame2d.imageBGRA_SRGB();
auto imageDataPointer = const_cast<void *>(static_cast<const void *>(sourceImage.data()));
cv::Mat image = cv::Mat(sourceImage.height(), sourceImage.width(), CV_8UC4, imageDataPointer).clone();
drawOverlay(image, linearResults, matrixResults);
Barcode Reading in Zivid Studio
Tip
Barcode reading in Zivid Studio does not require a software license.
You can easily test barcode reading using Zivid Studio. Connect to a camera and perform a 2D capture of a scene containing barcodes by selecting the barcode preset. Then click on View → Show barcodes to visualize decoded barcodes in the image.
Decoded barcodes visualized in Zivid Studio.
You can speed up barcode reading by selecting your specific barcode format in View → Configure barcodes to read.
Barcode Reading Performance
The performance of detection and decoding depends on multiple factors, including:
Barcode size
Distance to barcode
Image resolution
Image focus
Horizontal and vertical FOV
These factors effectively make up the spatial resolution on the barcode surface, which is important to maximize for reliable detection and decoding.
Image resolution and focus can be controlled by the camera settings, where we recommend BarcodeDetector::suggestSettings(camera) for optimal capture settings.
The camera’s horizontal and vertical FOV are fixed for each camera model, where larger FOVs lead to lower spatial resolution.
Distance to the barcode can be controlled by the application within some constraints, but is also limited by the camera’s working range.
The recommended cameras for barcode detection and decoding are therefore Zivid 2+ MR130 and MR60, as these provide sufficient spatial resolution within their working ranges. Below are some benchmarks for a variety of static barcodes qualified at different distances, orientations and placements within the FOV.
Tip
Stay within the green area for reliable decoding results.
Version History
SDK |
Changes |
|---|---|
2.19.0 |
Decoded barcodes now report their orientation in the image. |
2.18.0 |
Linear barcode detection and decoding are now separated into two steps.
|
2.17.0 |
Barcode detection API is added. |