Barcode Reading Tutorial

Introduction

This tutorial describes how to use Zivid SDK to detect and decode barcodes in a 2D image.

Prerequisites

Types of Supported Barcodes

바코드는 일반적으로 평행선, 공간 또는 도형 패턴으로 데이터를 시각적으로 기계가 읽을 수 있도록 표현한 것으로, 제품 번호와 같은 정보를 인코딩합니다. Zivid SDK는 다음과 같은 선형(1D) 및 행렬(2D) 바코드 형식을 지원합니다.

  • Linear: EAN-13, EAN-8, Code 128, Code 93, Code 39, UPC-A [1], UPC-E, ITF

  • Matrix: QR Code, Data Matrix

EAN-13 EAN-13
EAN-8 EAN-8
Code 128 Code 128
Code 93 Code 93
Code 39 Code 39
UPC-A UPC-A
UPC-E UPC-E
QR Code QR Code
Data Matrix Data Matrix

지원되는 바코드 형식의 예입니다.

바코드는 다양한 크기로 제공되며, 가장 작은 막대 또는 공간의 너비가 주요 크기 기준입니다. 이 가장 작은 요소를 모듈 크기 (또는 X-치수)라고 하며, 일반적으로 밀(mil) 단위로 표시되는데, 1밀은 1/1000인치(0.0254mm)입니다. 예를 들어, 표준 소매용 선형 바코드는 일반적으로 7밀(0.178mm)에서 13밀(0.330mm) 사이입니다. 바코드가 작을수록 안정적으로 감지하고 디코딩하려면 더 높은 해상도가 필요합니다.

8 mil 8 mil
10 mil 10 mil
12 mil 12 mil

동일한 거리에서 캡처한 다양한 Code 128 바코드 크기의 예입니다.

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.

바코드 감지기를 초기화하는 것부터 시작하세요. 이 작업은 한 번만 수행해야 하며, 매번 캡처할 때마다 수행해서는 안 됩니다.

소스로 이동

source

const auto barcodeDetector = Zivid::Experimental::Toolbox::BarcodeDetector();
소스로 이동

source

barcode_detector = BarcodeDetector()

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.

소스로 이동

source

// 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;
소스로 이동

source

# 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}

바코드를 성공적으로 감지하고 디코딩하려면 선명하고 노출이 잘 된 2D 이미지가 매우 중요합니다. 바코드 감지기에서 권장하는 2D 설정을 사용하여 2D 프레임을 캡처하세요.

소스로 이동

source

const auto settings2d = barcodeDetector.suggestSettings(camera);
const auto frame2d = camera.capture2D(settings2d);
소스로 이동

source

settings_2d = barcode_detector.suggest_settings(camera)
frame_2d = camera.capture_2d(settings_2d)

Detecting

선형 바코드 후보 영역을 감지합니다:

소스로 이동

source

const auto detectionResults = barcodeDetector.detectLinearCodes(frame2d);
소스로 이동

source

detection_results = barcode_detector.detect_linear_codes(frame_2d)

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.

소스로 이동

source

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;
}
소스로 이동

source

if detection_results:
    print(f"Detected {len(detection_results)} linear barcode candidates:")
    for i, candidate in enumerate(detection_results):
        print(f"-- Candidate {i + 1}:")
        print(f"   Bounding box: {candidate.bounding_box()}")
else:
    print("No linear barcode candidates detected")

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:

소스로 이동

source

const auto decodingResults = barcodeDetector.decodeLinearCodes(detectionResults, linearFormatFilter);
소스로 이동

source

decoding_results = barcode_detector.decode_linear_codes(detection_results, linear_format_filter)

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.

Barcodes in a camera image, each with a green bounding box, its decoded code, and an orange arrow showing its read direction.

Arrows show each barcode’s read direction. 0 degrees points right, and angles increase clockwise.

Print the decoded results:

소스로 이동

source

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;
}
소스로 이동

source

if decoded is not None:
    print(f"   Code:         {decoded.code()}")
    print(f"   Format:       {decoded.code_format()}")
    print(f"   Bounding box: {decoded.bounding_box()}")
    print(f"   Orientation:  {decoded.orientation()} ({decoded.orientation().angle_in_degrees():.1f} degrees)")
else:
    print("   Failed to decode")

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.

소스로 이동

source

// Reading all formats here; passing only the formats you use is faster and more reliable
const auto linearResults = barcodeDetector.readLinearCodes(frame2d);
소스로 이동

source

# Reading all formats here; passing only the formats you use is faster and more reliable
linear_results = barcode_detector.read_linear_codes(frame_2d)

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:

소스로 이동

source

const auto matrixBarcodeResults = barcodeDetector.readMatrixCodes(frame2d, matrixFormatFilter);
소스로 이동

source

matrix_barcode_results = barcode_detector.read_matrix_codes(frame_2d, matrix_format_filter)

해당 API에 대해서는 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:

소스로 이동

source

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;
}
소스로 이동

source

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:

소스로 이동

source

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);
소스로 이동

source

frame_2d = camera.capture_2d(settings_2d)
image = frame_2d.image_bgr_srgb().copy_data()
_draw_overlay(image, linear_results, matrix_results)

Barcode Reading in Zivid Studio

팁

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.

Barcode reading in Zivid Studio

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

탐지 및 디코딩 성능은 다음을 포함한 여러 요인에 따라 달라집니다.

  • 바코드 크기

  • 바코드까지의 거리

  • 이미지 해상도

  • 이미지 초점

  • 수평 및 수직 FOV

이러한 요소들은 바코드 표면의 공간적 해상도를 효과적으로 구성하는데, 이는 안정적인 감지와 디코딩을 위해 최대화하는 것이 중요합니다.

이미지 해상도와 초점은 카메라 설정으로 제어할 수 있으며, 최적의 촬영 설정을 위해 BarcodeDetector::suggestSettings(camera) 권장합니다. 카메라의 수평 및 수직 FOV는 각 카메라 모델마다 고정되어 있으며, FOV가 클수록 공간 해상도가 낮아집니다. 바코드까지의 거리는 애플리케이션에서 어느 정도 제한 조건 내에서 제어할 수 있지만, 카메라의 작동 범위에 따라서도 제한됩니다.

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.

팁

신뢰할 수 있는 디코딩 결과를 얻으려면 녹색 영역 내에 머물러야 합니다.

Version History

SDK

Changes

2.19.0

Decoded barcodes now report their orientation in the image.

2.18.0

선형 바코드 감지 및 디코딩이 이제 두 단계로 분리되었습니다. detectLinearCodes 는 후보 영역을 LinearBarcodeDetectionResult 로 반환합니다. decodeLinearCodes 는 감지 결과를 받아 디코딩된 코드를 LinearBarcodeDecodingResult 로 반환합니다. MatrixBarcodeDetectionResult 는 MatrixBarcodeDecodingResult 로 이름이 변경되었습니다. 모든 결과 유형은 이제 경계 상자를 제공합니다. ITF(Interleaved 2 of 5)가 이제 지원되는 선형 바코드 형식으로 추가되었습니다. UPC-A 코드는 이제 EAN-13으로 반환됩니다(UPC-A는 EAN-13의 유효한 하위 집합입니다). 단, 형식 필터에 UPC-A만 있는 경우는 예외입니다.

2.17.0

Barcode detection API가 추가되었습니다.