// ZBar_test.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include "stdafx.h"
#include "include\zbar.h"
#include "opencv2/opencv.hpp"
#include "opencv2/core.hpp"
#include "highgui.h"
#include <iostream>
using namespace std;
using namespace zbar;
using namespace cv;
string ZbarDecoder(Mat img)
{
cv::namedWindow("Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Image", img);
string result;
ImageScanner scanner;
const void *raw = (&img)->data;
// configure the reader
scanner.set_config(ZBAR_QRCODE, ZBAR_CFG_ENABLE, 1);
// wrap image data
Image image(img.cols, img.rows, "Y800", raw, img.cols * img.rows);
// scan the image for barcodes
int n = scanner.scan(image);
// extract results
Image::SymbolIterator symbol = image.symbol_begin();
if (image.symbol_begin() == image.symbol_end())
{
cout << "Check Image Please" << endl;
}
for (; symbol != image.symbol_end(); ++symbol)
{
cout << "Code Type:" << endl << symbol->get_type_name() << endl << endl;
cout << "Code Data:" << endl << symbol->get_data() << endl << endl;
}
image.set_data(NULL, 0);
return result;
}
string GetQRInBinImg(Mat binImg)
{
string result = ZbarDecoder(binImg);
if (result.empty())
{
Mat openImg;
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(binImg, openImg, MORPH_OPEN, element);
result = ZbarDecoder(openImg);
}
return result;
}
string GetQR(Mat img)
{
Mat binImg;
double thre = threshold(img, binImg, 0, 255, cv::THRESH_OTSU);
string result;
while (result.empty() && thre<255)
{
threshold(img, binImg, thre, 255, cv::THRESH_BINARY);
result = GetQRInBinImg(binImg);
thre += 20;
}
return result;
}
int main(int argc, char*argv[])
{
Mat src = imread("barcode.png");
cv::namedWindow("Source Image", cv::WINDOW_AUTOSIZE);
if (!src.data)
{
cout << "image null" << endl;
return 0;
}
cv::imshow("Source Image", src);
cv::cvtColor(src, src, CV_RGB2GRAY);
string re = GetQR(src);
cout << re << endl;
cv::waitKey();
return 0;
}