Use the zbar library to identify barcodes and QR codes

1. Graphic coding category

1.1 Barcode

A barcode is a graphic identifier that expresses a set of information by arranging multiple black bars and blanks of varying widths according to certain encoding rules. A common barcode is a parallel line pattern composed of black bars (referred to as bars) and white bars (referred to as spaces) with very different reflectivities.

Common barcodes include: Code39 code (standard 39 code), Codabar code (Cudabar code), Code25 code (standard 25 code), ITF25 code (interleaved 25 code), Matrix25 code (matrix 25 code), UPC-A code , UPC-E code, EAN-13 code (EAN-13 international commodity barcode), EAN-8 code (EAN-8 international commodity barcode), China postal code (a variant of matrix 25 code), Code-B code , MSI code, Code11 code, Code93 code, ISBN code, ISSN code, Code128 code (Code128 code, including EAN128 code), Code39EMS (EMS-specific 39 code) and other one-dimensional barcodes and two-dimensional barcodes such as PDF417. For more barcode knowledge, please refer to: https://zhuanlan.zhihu.com/p/582084617常见的商品条形码为code128

Barcodes can indicate the country of production, manufacturer, product name, production date, book classification number, starting and ending location of the mail, category, date and many other information. It also has the advantages of fast information collection, high reliability, large amount of information collected, flexibility, practicality, large degree of freedom, and easy production. Therefore, it has been widely used in many fields such as commodity circulation, library management, postal management, and banking systems.

Common barcodes are as shown below:

Insert image description here

1.2 QR code

QR code is also called 2D barcode. The common QR code is QR Code. QR stands for Quick Response, which is a coding method. It can store more information than the traditional Bar Code and can also represent more data types.

2-dimensional bar code is a black and white graphic that records data symbol information and is distributed on a plane (in a two-dimensional direction) according to certain rules with certain geometric figures. In code compilation It cleverly uses the concept of "0" and "1" bit streams that form the basis of computer internal logic, uses several geometric shapes corresponding to binary to represent text numerical information, and automatically reads it through image input equipment or photoelectric scanning equipment. To realize automatic processing of information: it has some common features of barcode technology: each code system has its own specific character set; each character occupies a certain width; it has certain verification functions, etc. At the same time, it also has the function of automatically identifying different lines of information and processing graphics rotation change points.

QR code has the characteristics of large amount of information, easy identification, and low cost. Therefore, it has been widely used in many fields such as scan code payment, commercial activities, network links, e-commerce platforms, etc.
The common QR code is as shown in the figure below:
Insert image description here
The structure description of the QR code is as shown in the figure below:

Insert image description here

2. Introduction to QR code recognition library

2.1 Quirk

QR code is a high-density matrix barcode. Quirc is a QR code library based on C/C++ that extracts and decodes QR codes from images. Some of its functions also need to be implemented together with the OpenCV library, such as quirc-demo-opencv (ie, graphics display); inspect-opencv (test).
Features:

  • 1. Fast enough for real-time video: On a modern x86 core, extracting and decoding from a VGA frame takes about 50 milliseconds.
  • 2. Has a robust and tolerant recognition algorithm. QR codes that are rotated and/or tilted toward the camera can be correctly recognized and decoded. It can also differentiate and decode multiple codes in the same image.
  • 3. Easy to use, with a simple API described in a single annotated header file.
  • 4. It is small, easy to embed, and has no dependencies other than standard C functions.
  • 5. Its memory footprint is very small: one byte per image pixel, plus a few kB per decoder object.
  • 6. Does not use global mutable state and can be used safely in multi-threaded applications.
  • 7.BSD licensed with few restrictions on use and/or modification. In addition to the libraries, the distribution also comes with some test programs.

简单的来概括Quirc的特点就是:简单,方便移植,识别准确率高. For specific usage methods, please refer to its official website: https://github.com/dlbeer/quirc

2.2 OpenCV

Opencv has two related APIs in the object detection module QRCodeDetector to implement QR code detection and QR code parsing respectively.
1. Detection API points = QRCodeDetector.detect(img)
Among them:
img is the input image, grayscale or color image; < a i=4> points outputs the coordinate information of the four points of the QR code

2. Recognition API straight_qrcode = QRCodeDetector.decode(img, points)
Among them:
img is the input image, grayscale or color image;
Points is the vertex coordinate of the minimum circumscribed rectangle of the QR code ROI;
straight_qrcode output is the QR code utf-8 string returned by the ROI image information of the QR code area;

3. Combined detection and recognition API
points,straight_qrcode = QRCodeDetector.detectAndDecode(img)
Among them:
img is the input image, grayscale or color image;
points outputs the vertex coordinates of the minimum circumscribed rectangle of the QR code ROI;
straight_qrcode outputs the QR code utf-8 string returned by the ROI image information of the QR code area; a>

For its use cases of C++ recognition of QR codes, please refer to: https://blog.csdn.net/u014072827/article/details/112270853.

opencv4 以上可以对二维码进行检测并识别,但在使用过程中发现,其效果不是特别好, 在很多情况识别失败, 而且不支持barcode失败

2.3 ZXing (“zebra crossing”)

ZXing is an open source, multi-format one-dimensional/two-dimensional barcode image processing library implemented in Java. It includes ports to other languages. zxing can use the built-in camera of your mobile phone to scan and decode barcodes.

basic skills:

  • Scan the QR code image through the camera and read the image content
  • Select a QR code picture from the album and read the picture content
  • Enter the string content yourself and generate a QR code image
  • Long press to identify the QR code image generated by yourself

2.4 ZBar

ZBar is an open source software suite for reading barcodes from a variety of sources, such as video streams, image files, and raw intensity sensors. It supports many popular symbologies (barcode types) including EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5, and QR codes.

Flexible layered implementation facilitates barcode scanning and decoding for any application: Use independently from the included GUI and command line programs, easily integrate the barcode scanning widget into your Qt, GTK+ or PyGTK GUI applications.

Features
*Cross-platform - Linux/Unix, Windows, iPhone®, embedded...
*High speed - real-time scanning of video streams *Modular components can be used together or individually *Suitable for embedded applications, using low-cost processors/ Hardware *Not limited to images, no floating point operations
*Small memory usage


2.5 Conclusion

Which library to choose depends on your application. If the QR code is relatively standard, BoofCV (an open source, real-time computer vision library implemented in Java) is recommended. Its detection accuracy is high and the speed is also very good. If If the QR code is defaced or has a changed appearance, ZXing is a good choice. If you can only use C++, Zbar is recommended. OpenCV is undoubtedly the worst.
For specific results comparing several major open source libraries for QR code recognition and detection, please refer to:
https://blog.csdn.net/yangdashi888/article/details /99093756

3. Installation and use of Zbar library

3.1 Zbar library installation

The Zbar library provides 32-bit library files by default. Its download and installation address is: https://zbar.sourceforge.net/download.html. Windows users can install the following link on the official website to download. After downloading the software Click all the way to select the default. After installing the software, you need to add the zbar/bin path to the system environment variable path.
Insert image description here
If it is a 64-bit computer, you can download the 64-bit zbar library from the following link. ZBar library (including 64-bit library and 32-bit library files) installation-free version

For more zbar library installation and configuration details, please refer to: C++ uses Zbar to identify QR codes

3.2 Configuration vs environment

Using zbar for QR code recognition requires relying on opencv for image reading. Therefore, zbar and opencv need to be configured.
For the installation of opencv, please refer to opencv 1. Basic operating environment configuration (download and installation, writing code, configuration environment)

Configuration details
The configuration of include directory, lib directory and lib file is as follows. Pay attention to these configurations and operating environment (the red area in the figure below is the Release 64-bit environment. This configuration are invalid in other contexts) are closely related.
Insert image description here
Insert image description here

3.3 Use cases

The specific use cases are as follows. The zbar library can be called through the recognition_qrcode function to complete QR code recognition and return the recognition results.使用zbar进行二维码识别时,识别性能与图像尺寸密切相关,当图像尺寸较大时,识别时间较长,可以通过对图像进行resize来提升识别速度


#include <iostream>
#include "zbar.h"
#include "string.h"
#include <opencv2/opencv.hpp>
#include <chrono>
using namespace std;
using namespace zbar;  //添加zbar名称空间      
using namespace cv;

string recognition_qrcode(cv::Mat image)
{
    
    
    zbar::ImageScanner scanner;
    scanner.set_config(zbar::ZBAR_NONE, zbar::ZBAR_CFG_ENABLE, 1);
    auto beforeTime = std::chrono::steady_clock::now();
    int width = image.cols;
    int height = image.rows;
    uchar* raw = (uchar*)image.data;
    zbar::Image imageZbar(width, height, "Y800", raw, width * height);
    scanner.scan(imageZbar); //扫描条码  
    zbar::Image::SymbolIterator symbol = imageZbar.symbol_begin();
    if (imageZbar.symbol_begin() == imageZbar.symbol_end())
    {
    
    
        std::cout << "查询条码失败,请检查图片!" << std::endl;
    }
    string result;
    for (; symbol != imageZbar.symbol_end(); ++symbol)
    {
    
    
        std::cout << "类型:" << symbol->get_type_name() << std::endl;
        std::cout << "条码:" << symbol->get_data() << std::endl;
        result = symbol->get_type_name() + ":"+ symbol->get_data();
    }
   // cv:imshow("Source Image", image);
    //cv::waitKey();
    auto afterTime = std::chrono::steady_clock::now();

    std::cout << "总耗时:" << std::endl;
    //毫秒级
    double duration_millsecond = std::chrono::duration<double, std::milli>(afterTime - beforeTime).count();
    std::cout << duration_millsecond << "毫秒" << std::endl;

    return result;
}

int main(int argc, char* argv[]) {
    
    
    std::string path = "D:\\二维码识别\\t2.png";
    Mat imageSource = imread(path, 0);
    if (imageSource.cols >= 2048) {
    
    
        resize(imageSource, imageSource, {
    
    }, 0.25, 0.25);
        std::cout << "图像被resize了!!!!" << std::endl;
    }
    string res = recognition_qrcode(imageSource);
    imshow("res", imageSource);
    waitKey();
}

The QR code recognition effect is as follows
Insert image description here
The barcode recognition effect is as follows
Insert image description here

3.4 Usage tips

In some complex image scenarios, the zbar library may not be able to recognize barcodes or QR codes. This is not because zbar’s performance is poor, but because it cannot accurately find the object to be recognized. We can design our own algorithm to first achieve rough positioning of barcodes or QR codes, increase the proportion of barcodes or QR codes in the original image, and then use the zbar library to identify QR codes or barcodes.
Among them, for the rough positioning of the QR code, you can refer to: Opencv rough positioning extraction of the fourteenth QR code, about For rough positioning of barcodes, you can also refer to the ideas in this blog post.

Guess you like

Origin blog.csdn.net/m0_74259636/article/details/134742584