基于 libdmtx和zxing的DM二维码识别总结

基于 libdmtx和zxing的DM二维码识别总结

  • 1.基于libdmtx的DM二维码识别
    • 1.1 python实现
    • 1.2 C++实现
  • 2. 基于zxing的DM二维码识别
    • 2.1 C++实现

1.基于libdmtx的DM二维码识别

1.1 python实现

python识别DM二维码比较简单,只需要pylibdmtx 库即可,pylibdmtx 库包含了libdmtx的功能,python代码如下。

# -*-coding:utf-8 -*-
import time
import cv2
from pylibdmtx import pylibdmtx
# 加载图片
image = cv2.imread('1.bmp')
t0 = time.time()
# 解析二维码
all_barcode_info = pylibdmtx.decode(image, timeout=500, max_count=1)
print(all_barcode_info)
print(time.time() - t0)
print(all_barcode_info[0].data.decode("utf-8"))

1.2 C++实现

用c++实现DM二维码识别相对复杂,需要用到libdmtx.lib 和dmtx.h头文件。编译libdmtx.lib比较复杂,所以我很贴心的附上X86和X64环境下的libdmtx.lib、libdmtx.dll链接库,以及dmtx.h。百度网盘链接为:https://pan.baidu.com/s/1e0DK7PiAFAIzLwempsNacg 提取码:ckux

C++实现代码如下:

#include 
#include 
#include "dmtx.h"

using namespace cv;
using namespace std;

int main()
{
	DmtxMessage* msg;
	DmtxRegion* reg;
	Mat dst;
	double time = getTickCount();
	Mat src = imread("1.jpg");
	if (!src.data)
	{
		cout << "Load image failed!" << endl;
	}
	cvtColor(src, src, COLOR_BGR2GRAY);
	DmtxImage* image;
	image = dmtxImageCreate(src.data, src.cols, src.rows, DmtxPack8bppK);//注意图片类型
	DmtxDecode* dec = dmtxDecodeCreate(image, 1);//解码
	reg = dmtxRegionFindNext(dec, NULL);        //获取二维码位置,第二个参数表示扫描时间上限,达到时间上限退出扫描
	if (reg != NULL) {
		msg = dmtxDecodeMatrixRegion(dec, reg, 1);//解码信息
		if (msg != NULL)
		{
			cout << msg->output << endl;
			dmtxMessageDestroy(&msg);
		}
		dmtxRegionDestroy(&reg);
	}
	else
	{
		cout << "Get region failed!" << endl;
	}
	dmtxDecodeDestroy(&dec);
	dmtxImageDestroy(&image);
	time = (getTickCount() - time) / getTickFrequency();
	cout << "the processing time is :" << time << endl;
	cin.get();
	return 0;
}

2. 基于zxing的DM二维码识别

2.1 C++实现

zxing是一个比较知名的二维码识别开源库。直接抄作业吧,VS工程以及所有和zxing相关的依赖项均在此链接:
链接:https://pan.baidu.com/s/1_aQ-EqaQ4TZdEefO0AF9Qg
提取码:o72j


#include "ReadBarcode.h"
#include "TextUtfEncoding.h"

#include 
#include 
#include 
#include 
#include 
#include

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

using namespace ZXing;

static void PrintUsage(const char* exePath)
{
	std::cout << "Usage: " << exePath << " [-fast] [-norotate] [-format ] [-ispure] \n"
		<< "    -fast      Skip some lines/pixels during detection (faster)\n"
		<< "    -norotate  Don't try rotated image during detection (faster)\n"
		<< "    -format    Only detect given format(s) (faster)\n"
		<< "    -ispure    Assume the image contains only a 'pure'/perfect code (faster)\n"
		<< "\n"
		<< "Supported formats are:\n";
	for (auto f : BarcodeFormats::all()) {
		std::cout << "    " << ToString(f) << "\n";
	}
	std::cout << "Formats can be lowercase, with or without '-', separated by ',' and/or '|'\n";
}

static bool ParseOptions(int argc, char* argv[], DecodeHints* hints, std::string* filePath)
{
	for (int i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-fast") == 0) {
			hints->setTryHarder(false);
		}
		else if (strcmp(argv[i], "-norotate") == 0) {
			hints->setTryRotate(false);
		}
		else if (strcmp(argv[i], "-ispure") == 0) {
			hints->setIsPure(true);
			hints->setBinarizer(Binarizer::FixedThreshold);
		}
		else if (strcmp(argv[i], "-format") == 0) {
			if (++i == argc)
				return false;
			try {
				hints->setFormats(BarcodeFormatsFromString(argv[i]));
			}
			catch (const std::exception& e) {
				std::cerr << e.what() << "\n";
				return false;
			}
		}
		else {
			*filePath = argv[i];
		}
	}

	return !filePath->empty();
}

std::ostream& operator<<(std::ostream& os, const Position& points) {
	for (const auto& p : points)
		os << p.x << "x" << p.y << " ";
	return os;
}

int main(int argc, char* argv[])
{
	DecodeHints hints;
        //自己修改二维码路径
	std::string filePath = "C:/Users/admin/Desktop/DM_Rec/imgs/7.jpg";

	if (!ParseOptions(argc, argv, &hints, &filePath)) {
		PrintUsage(argv[0]);
		return -1;
	}

	int width, height, channels;

	clock_t startTime, endTime;
	
	std::unique_ptr<stbi_uc, void(*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, 4), stbi_image_free);
	if (buffer == nullptr) {
		std::cerr << "Failed to read image: " << filePath << "\n";
		return -1;
	}
	startTime = clock();//计时开始
	auto result = ReadBarcode({ buffer.get(), width, height, ImageFormat::RGBX }, hints);
	endTime = clock();//计时结束
	std::cout << "Text:     \"" << TextUtfEncoding::ToUtf8(result.text()) << "\"\n"
		<< "Format:   " << ToString(result.format()) << "\n"
		<< "Position: " << result.position() << "\n"
		<< "Rotation: " << result.orientation() << " deg\n"
		<< "Error:    " << ToString(result.status()) << "\n";
	std::cout << "The run time is: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << std::endl;
	std::map<ResultMetadata::Key, const char*> keys = { {ResultMetadata::ERROR_CORRECTION_LEVEL, "EC Level: "},
													   {ResultMetadata::SUGGESTED_PRICE, "Price:    "},
													   {ResultMetadata::ISSUE_NUMBER, "Issue #:  "},
													   {ResultMetadata::POSSIBLE_COUNTRY, "Country:  "},
													   {ResultMetadata::UPC_EAN_EXTENSION, "Extension:"} };

	for (auto key : keys) {
		auto value = TextUtfEncoding::ToUtf8(result.metadata().getString(key.first));
		if (value.size())
			std::cout << key.second << value << "\n";
	}

	return static_cast<int>(result.status());
}

你可能感兴趣的:(OCR,c++,opencv,opencv,c++,人工智能)