这个程序主要用zbar解码库来解析二维码的,ZBar是一个开源软件套件,用于从各种来源读取条形码,例如视频流,图像文件和原始强度传感器。 它支持许多流行的符号(条形码类型),包括EAN-13 / UPC-A,UPC-E,EAN-8,Code 128,Code 39,Interleaved 2 of 5和QR Code。
这里用电脑自带的WebCam采集图像,并对每一帧都进行识别,然后检测到码信息时将其写入到当前目录下的文件中方便观察,请看代码:
#include "zbar.h"
#include "cv.h"
#include "highgui.h"
#include "iostream"
#include "fstream"
using namespace std;
using namespace zbar; //添加zbar名称空间
using namespace cv;
int main(int argc, char*argv[])
{
VideoCapture VC(0);
while (true)
{
ImageScanner scanner;
scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);
Mat image;
VC.read(image);
imshow("Source Image", image);
if (!image.data)
{
cout << "请确认摄像头正确采集" << endl;
system("pause");
return 0;
}
Mat imageGray;
cvtColor(image, imageGray, CV_RGB2GRAY);
int width = imageGray.cols;
int height = imageGray.rows;
uchar *raw = (uchar *)imageGray.data;
Image imageZbar(width, height, "Y800", raw, width * height);
scanner.scan(imageZbar); //扫描条码
Image::SymbolIterator symbol = imageZbar.symbol_begin();
if (imageZbar.symbol_begin() == imageZbar.symbol_end())
{
cout << "查询条码失败,请检查图片!" << endl;
}
else
{
for (; symbol != imageZbar.symbol_end(); ++symbol)
{
cout << "类型:" << endl << symbol->get_type_name() << endl << endl;
cout << "条码:" << endl << symbol->get_data() << endl << endl;
//将检测的结果写到result.txt中方便查阅,追加方式写入的,
ofstream fout("result.txt", ios::app);
fout << "类型:" << symbol->get_type_name() << endl << "条码:" << symbol->get_data() << endl<<endl;
fout.close();
int key = cvWaitKey();
if (key == 27) return 0;
}
}
imageZbar.set_data(NULL, 0);
int key = cvWaitKey(100);
if (key == 27) return 0;
}
waitKey();
return 0;
}
首先要去官网下载ZBar 0.10 Windows installer,然后将其库安装本地,将zbar/bin目录添加到系统的环境变量,然后将zbar/lib添加到VS的项目/属性/VC++目录/包含目录下,将zbar/include 添加到VC++目录/库目录下,在链接器-输入中添加libzbar-0.lib ,完工,运行代码试试吧!