二维码Data Matrix的解码实现(zxing-cpp)

二维码Data Matrix的介绍可以参考http://blog.csdn.net/fengbingchun/article/details/44279967 ,以下是通过zxing-cpp开源库实现的对Data Matrix进行解码的测试代码:

#include "funset.hpp"
#include <string>
#include <fstream>
#include <Windows.h>

#include <zxing/LuminanceSource.h>
#include <zxing/common/Counted.h>
#include <zxing/Reader.h>
#include <zxing/aztec/AztecReader.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include <zxing/DecodeHints.h>
#include <zxing/datamatrix/DataMatrixReader.h>

#include <opencv2/opencv.hpp>

#include "zxing/MatSource.h"

static void utf8_to_gbk(const char* utf8, char* gbk) {
	const int maxlen = 128;
	wchar_t unicode_str[maxlen];
	int outlen = MultiByteToWideChar(CP_UTF8, 0, utf8, strlen(utf8), unicode_str, maxlen);
	outlen = WideCharToMultiByte(CP_ACP, 0, unicode_str, outlen, gbk, 128, NULL, NULL);
	gbk[outlen] = '\0';
}

int test_DataMatrix_decode()
{
	std::string image_name = "E:/GitCode/BarCode_Test/test_images/data_matrix_encode.jpg";
	cv::Mat matSrc = cv::imread(image_name, 1);
	if (!matSrc.data) {
		fprintf(stderr, "read image error: %s", image_name.c_str());
		return -1;
	}
	
	cv::Mat matGray;
	cv::cvtColor(matSrc, matGray, CV_BGR2GRAY);
	
	zxing::Ref<zxing::LuminanceSource> source = MatSource::create(matGray);
	int width = source->getWidth();
	int height = source->getHeight();
	fprintf(stderr, "image width: %d, height: %d\n", width, height);
	
	zxing::Ref<zxing::Reader> reader;
	reader.reset(new zxing::datamatrix::DataMatrixReader);
	
	zxing::Ref<zxing::Binarizer> binarizer(new zxing::GlobalHistogramBinarizer(source));
	zxing::Ref<zxing::BinaryBitmap> bitmap(new zxing::BinaryBitmap(binarizer));
	zxing::Ref<zxing::Result> result(reader->decode(bitmap, zxing::DecodeHints(zxing::DecodeHints::DATA_MATRIX_HINT)));
	
	std::string txt = "E:/GitCode/BarCode_Test/test_images/data_matrix_encode.txt";
	std::ifstream in(txt);
	if (!in.is_open()) {
		fprintf(stderr, "fail to open file: %s\n", txt.c_str());
		return -1;
	}

	std::string str1;
	std::getline(in, str1);
	char tmp[128];
	utf8_to_gbk(str1.c_str(), tmp);
	std::string ret = std::string(tmp);
	fprintf(stderr, "actual        result: %s\n", ret.c_str());
	std::string str2 = result->getText()->getText();
	fprintf(stdout, "recognization result: %s\n", str2.c_str());
	
	if (ret.compare(str2) == 0) {
		fprintf(stderr, "=====  recognition is correct  =====\n");
	}
	else {
		fprintf(stderr, "=====  recognition is wrong =====\n");
		return -1;
	}
	
	in.close();
	
	return 0;
}
测试图像如下:

输出结果如下:


GitHubhttps://github.com/fengbingchun/Barcode_Test



评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值