opencv calls Nu book / zxing CPP to identify QR code

Posted by AnarchistX on Thu, 26 Mar 2020 05:15:22 +0100

Environment installation:

1. The source code of zxing CPP and the lib generated after the source code compilation. My version is V1.0.8. The compilation method is as follows: https://www.cnblogs.com/zhenjin-huaxiazongdai/p/12545959.html . Zxing CPP project path: https://github.com/nu-book/zxing-cpp

2. Visual Studio 2017 installation https://visualstudio.microsoft.com/zh-hans/vs/older-downloads/ After installation, add "desktop development using C + + support" in tools - get tools and support.

3. Install windows opencv and add environment variables. For example, I install it in the D:\opencv\opencv folder and add environment variables: D:\opencv\opencv\build\x64\vc15\bin. We can also see from the opencv folder that opencv only supports x64 by default, and x86 needs to download the source code and compile by itself. I installed version 4.1.2, download path:

Demo address: https://github.com/SourceCode-Farmer/ZxingDemo

 

Process records:

1, Add dependency

1. Create a new Visual C++ Windows console application ZxingDemo, and open the project folder with the following files:

2. Open the build folder under the opencv installation directory, copy the include folder to the ZxingDemo project folder, and rename it to opencv header

3. Create a new opencv \ lib64 folder in the ZxingDemo project folder, open the build\x64\vc15\lib folder under the opencv installation directory, and copy the two files opencv \ world412.lib and opencv \ world412d.lib to the ZxingDemo project folder (if the name of the Lib file changes, please copy all the lib files together).

4. Create a new folder in the ZxingDemo project folder, copy the compiled lib of zxing CPP to the folder (note that the solution configuration and solution platform of zxing CPP and ZxingDemo must be the same at compile time).

5. Open the core folder in the source code of zxing CPP, copy src to the ZxingDemo project directory, and rename the folder to zxing header.

6. Open the "zxing" header folder and delete all cpp files in the current directory and its subdirectories.

ps: if only Qr code identification is done, you can delete the directories aztec, maxicode, one, pdf417 and textcodec, and keep the h files under the zxing header and the h files under the datamatrix and qrcode files.

ps: modify the file grouping basis to quickly delete cpp files

 

2, Configure dependencies

1. Right click the attribute of vs project, adjust the configuration to Release, and adjust the platform to x64

2. Attribute - configuration attribute - c/c + + - General - add the containing directory, add the path of header file (adjust the path of picture according to the actual situation, and follow the rules).

3. Properties - configuration properties - linker - General - additional library directory, add the lib Library Directory (adjust the image path according to the actual situation, and follow the rules).

4. Properties - configuration properties - linker - General - additional dependencies, add all lib file names in the ZxingDemo project (adjusted according to the actual names of lib files).

 

Three, encoding

1. Write the code in the file ZxingDemo.cpp.

//Adjust according to the actual path of the project
#pragma comment(lib,"zxing_lib/ZXingCore.lib")

#include "stdafx.h"

#include "zxing_header\HybridBinarizer.h"
#include "zxing_header\LuminanceSource.h"
#include "zxing_header\GenericLuminanceSource.h"
#include "zxing_header\DecodeHints.h"
#include "zxing_header\BinaryBitmap.h"
#include "zxing_header\ReadBarcode.h"
#include "zxing_header\TextUtfEncoding.h"
#include "zxing_header\MultiFormatReader.h"

#include <opencv2\opencv.hpp>
#include <opencv2\core\types_c.h>


static std::string WstringToString(const std::wstring &wstr) {
    std::string str;
    std::mbstate_t state = {};
    const wchar_t *data = wstr.data();
    size_t len = std::wcsrtombs(nullptr, &data, 0, &state);
    if (static_cast<size_t>(-1) != len) {
        std::unique_ptr<char[]> buff(new char[len + 1]);
        len = std::wcsrtombs(buff.get(), &data, len, &state);
        if (static_cast<size_t>(-1) != len) {
            str.assign(buff.get(), len);
        }
    }
    return str;
}

static void Scan() {
    cv::Mat mat, gray_mat;
    //Open the picture.
    mat = cv::imread("test.PNG");
    if (mat.empty()) {
        std::cout << "not found image" << std::endl;
        return;
    }
    //Convert to grayscale
    cv::cvtColor(mat, gray_mat, cv::COLOR_RGBA2GRAY);
    //Width height
    int height = gray_mat.rows;
    int width = gray_mat.cols;
    auto *pixels = new unsigned char[height * width];
    int index = 0;
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            pixels[index++] = gray_mat.at<unsigned char>(i, j);
        }
    }
    //Distinguish
    std::shared_ptr<ZXing::GenericLuminanceSource> luminance = std::make_shared<ZXing::GenericLuminanceSource>(0, 0, width, height, pixels, width * sizeof(unsigned char));
    std::shared_ptr<ZXing::BinaryBitmap> bitmap = std::make_shared<ZXing::HybridBinarizer>(luminance);
    ZXing::DecodeHints hints;
    //Add as needed format
    std::vector<ZXing::BarcodeFormat> formats = { ZXing::BarcodeFormat(ZXing::BarcodeFormat::QR_CODE) };
    hints.setPossibleFormats(formats);
    auto reader = new ZXing::MultiFormatReader(hints);
    ZXing::Result result = reader->read(*bitmap);
    if (result.status() == ZXing::DecodeStatus::NoError) {
        //Recognition successful, print results
        std::cout << WstringToString(result.text()) << std::endl;
    }
    else {
        std::cout << "Fail" << std::endl;
    }
}

int main()
{
    Scan();
    std::cin.get();
    return 0;
}

 

2. Make a QR code picture test.PNG and put it in the compiled output directory x64\Release.

 

Four. Start up

1. Adjust the configuration to Release, adjust the platform to x64, and click "local windows debugger" to start the test.

2. Output the result successfully.

5, FAQs

1. Compile exception: error C4996 'wcsrtombs': this function or variable may be unsafe. Adviser using wcsrtombs ﹣ s instead. To disable prediction, use ﹣ CRT ﹣ secure ﹣ no ﹣ warnings. See online help for details. ZxingDemo H:\cpp\ZxingDemo\ZxingDemo\ZxingDemo.cpp 23

Solution: right click the item attribute - configuration attribute - c/c + + - preprocessor - preprocessor definition, and add the following preprocessor definition.

_CRT_SECURE_NO_WARNINGS
_CRT_NONSTDC_NO_WARNINGS
_CRT_SECURE_NO_WARNINGS_GLOBALS

2. Execute an exception, and report an error after starting the test: This program cannot be started, because opencv · world412.dll is missing from the computer. An attempt to reinstall the program has resolved this problem.

Reason: the program can not find opencv · world412.dll, general situation: 1. Opencv is not installed or the opencv environment variable is not added. 2. The opencv environment variable is not added until vs2017 is opened, which is not effective.

Solution: install opencv and add the Path environment variable build\x64\vc15\bin (or build\x64\vc14\bin). Close Vs2017 and reopen the project.

Topics: C++ OpenCV Attribute Windows github